<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Exception;
use think\Loader;
use think\Request;

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');

        return $this->fetch();
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            echo "<pre>";
            print_r(Request()->param());
            exit;
        }
        $this->assign('title', '表单示例');

        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');

        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    public function test()
    {
        return $this->view->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');

        return $this->fetch();
    }

    /**
     * 文章分类列表
     * */
    public function articleTypeList()
    {
        $list = Db::name('article_type')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章分类列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章分类
     * */
    public function doArticleType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('article_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'name' => $name
            ];

            if ($id > 0) {
                $res = Db::name('article_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('article_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '新增文章分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('article_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '文章分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章分类
     * */
    public function delArticleType()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '分类ID缺失');

        $info = Db::name('article_type')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article_type')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $list = Db::name('article')->order('sort asc')->paginate()->each(
            function ($v) {
                $type_info = Db::name('article_type')->where(['id' => $v['type_id']])->find();
                $v['type_name'] = $type_info['name'];

                return $v;
            }
        );

        $type_list = Db::name('article_type')->select();

        $this->assign('list', $list);
        $this->assign('type_list', $type_list);
        $this->assign('title', '文章列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $vice_title = $input['vice_title'];
            $img = $input['img'];
            $type_id = $input['type_id'];
            $user_id = $input['user_id'];
            $sort = $input['sort'];
            $content = $input['content'];

            if (empty($title)) adminReturn(2, '请输入标题');
            if (empty($vice_title)) adminReturn(2, '请输入副标题');
            if (empty($img)) adminReturn(2, '请上传封面图');
            if (empty($type_id)) adminReturn(2, '请选择分类');
            if (empty($user_id)) adminReturn(2, '请选择作者');
            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'title' => $title,
                'vice_title' => $vice_title,
                'img' => $img,
                'type_id' => $type_id,
                'user_id' => $user_id,
                'sort' => $sort,
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('article')->where(['id' => $id])->find();
            }

            $type_list = Db::name('article_type')->select();

            $user_list = Db::name('user')->select();

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);
            $this->assign('type_list', $type_list);
            $this->assign('user_list', $user_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 规格-属性 列表
     * */
    public function skuList()
    {
        $list = Db::name('sku')->select();
        $this->assign('list', json_encode($list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '规格-属性');

        return $this->fetch();
    }

    /**
     * 新增/编辑 规格-属性
     * */
    public function doSku()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $pid = $input['pid'];
            $name = $input['name'];

            if (empty($name)) apiReturn(2, '请输入名称');

            if ($id) {
                $where['name'] = $name;
                $where['id'] = ['neq', $id];
                if ($pid) {
                    $where['pid'] = $pid;
                } else {
                    $where['pid'] = 0;
                }
                $count = Db::name('sku')->where($where)->count();

                $obj = $pid ? '属性' : '规格';
                if ($count > 0) apiReturn(2, '该' . $obj . '名称已存在');

                //编辑
                $data = [
                    'name' => $name,
                    'pid' => $pid
                ];

                $res = Db::name('sku')->where(['id' => $id])->cache('sku')->update($data);
                if ($res) {
                    apiReturn(1, '编辑成功');
                } else {
                    apiReturn(2, '编辑失败');
                }
            } else {
                $where['name'] = $name;
                if ($pid) {
                    $where['pid'] = $pid;
                } else {
                    $where['pid'] = 0;
                }

                $count = Db::name('sku')->where($where)->count();

                $obj = $pid ? '属性' : '规格';
                if ($count > 0) apiReturn(2, '该' . $obj . '名称已存在');

                //新增
                $data = [
                    'name' => $name,
                    'pid' => $pid
                ];

                $res = Db::name('sku')->insert($data);
                if ($res) {
                    cache('sku', null);
                    apiReturn(1, '新增成功');
                } else {
                    apiReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('sku')->where(['id' => $id])->find();
            } else {
                $info = [];
            }

            $sku_list = Db::name('sku')->where(['pid' => 0])->select();

            $data = [
                'info' => $info,
                'sku_list' => $sku_list
            ];

            apiReturn(1, '获取数据成功', $data);
        }
    }

    /**
     * 删除 规格-属性
     * */
    public function delSku()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pid = $input['pid'];

        $obj = $pid ? '属性' : '规格';
        if (empty($id)) apiReturn(2, $obj . 'ID缺失');

        Db::startTrans();
        try {
            Db::name('sku')->where(['id' => $id])->cache('sku')->delete();
            if ($pid == 0) Db::name('sku')->where(['pid' => $id])->delete();

            Db::commit();
            apiReturn(1, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 商品分类列表
     * */
    public function goodsTypeList()
    {
        $list = Db::name('goods_type')->where(['pid' => 0])->order('sort asc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '商品分类列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 商品分类
     * */
    public function doGoodsType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $pid = $input['pid'] ? : 0;
            $img = $input['img'] ? : 0;
            $name = $input['name'];
            $sort = $input['sort'] ? : 0;

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($pid) $where['pid'] = $pid;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('goods_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'pid' => $pid,
                'name' => $name,
                'img' => $img,
                'sort' => $sort
            ];

            if ($id > 0) {
                $res = Db::name('goods_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑商品分类成功', url('goodsTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('goods_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增商品分类成功', url('goodsTypeList'));
                } else {
                    adminReturn(2, '新增商品分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('goods_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '商品分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除商品分类
     * */
    public function delGoodsType()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pid = $input['pid'];

        if (empty($id)) adminReturn(2, '分类ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('goods_type')->where(['id' => $id])->find();
            if ($info) {
                Db::name('goods_type')->where(['id' => $id])->delete();
                if ($pid == 0) Db::name('goods_type')->where(['pid' => $id])->delete();

                Db::commit();
                adminReturn(1, '删除成功');
            } else {
                Db::rollback();
                adminReturn(2, '数据不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 商品品牌列表
     * */
    public function goodsBrandList()
    {
        $list = Db::name('goods_brand')->order('sort asc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '商品品牌列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 商品品牌
     * */
    public function doGoodsBrand()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $sort = $input['sort'] ? : 0;

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('goods_brand')->where($where)->count();
            if ($count > 0) adminReturn(2, '该品牌已存在');

            $data = [
                'name' => $name,
                'sort' => $sort
            ];

            if ($id > 0) {
                $res = Db::name('goods_brand')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑商品品牌成功', url('goodsBrandList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('goods_brand')->insert($data);
                if ($res) {
                    adminReturn(1, '新增商品品牌成功', url('goodsBrandList'));
                } else {
                    adminReturn(2, '新增商品品牌失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('goods_brand')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '商品品牌');

            return $this->view->fetch();
        }
    }

    /**
     * 删除商品分类
     * */
    public function delGoodsBrand()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, '品牌ID缺失');

        $info = Db::name('goods_brand')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('goods_brand')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 运费模板
     * */
    public function freightList()
    {
        $list = Db::name('freight')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '运费模板');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 运费模板
     * */
    public function doFreight()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $type = $input['type'];
            $init_count = $input['init_count'];
            $init_count_price = $input['init_count_price'];
            $inc_count = $input['inc_count'];
            $inc_count_price = $input['inc_count_price'];
            $init_weight = $input['init_weight'];
            $init_weight_price = $input['init_weight_price'];
            $inc_weight = $input['inc_weight'];
            $inc_weight_price = $input['inc_weight_price'];
            $diff_freight = $input['diff_freight'];

            if (empty($name)) apiReturn(2, '请输入模板名称');

            $where['name'] = $name;
            if ($id > 0) $where['id'] = ['neq', $id];
            $count = Db::name('freight')->where($where)->count();
            if ($count > 0) adminReturn(2, '模板名称已存在');

            /*if (($type == 1 && (empty($init_count) || empty($init_count_price) || empty($inc_count) || empty($inc_count_price)))
                ||
                ($type == 2 && (empty($init_weight) || empty($init_weight_price) || empty($inc_weight) || empty($inc_weight_price)))
            ) adminReturn(2, '请完善计价规格');*/

            $time = time();
            $data = [
                'name' => $name,
                'type' => $type,
                'init_count' => $init_count,
                'init_count_price' => $init_count_price,
                'inc_count' => $inc_count,
                'inc_count_price' => $inc_count_price,
                'init_weight' => $init_weight,
                'init_weight_price' => $init_weight_price,
                'inc_weight' => $inc_weight,
                'inc_weight_price' => $inc_weight_price,
                'diff_freight' => $diff_freight,
            ];

            if ($id > 0) {
                // 编辑
                $data['update_time'] = $time;
                $res = Db::name('freight')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('freightList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                // 新增
                $data['create_time'] = $time;
                $res = Db::name('freight')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('freightList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('freight')->where(['id' => $id])->find();

            $province_list = Db::name('province')->field('province_id,name province_name')->select();
            if ($province_list) {
                foreach ($province_list as &$v) {
                    $city_list = Db::name('city')->field('city_id,name city_name')->where(['province_id' => $v['province_id']])->select();
                    $v['city_list'] = $city_list;
                }
            }

            $info['diff_freight_list'] = json_decode($info['diff_freight'], true);
            $this->assign('diff_freight_data', $info['diff_freight'] ? $info['diff_freight'] : json_encode([]));
            $this->assign('info', $info);
            $this->assign('province_list', $province_list);
            $this->assign('title', ($id ? '编辑' : '新增') . '运费模板');

            return $this->view->fetch();
        }
    }

    /**
     * 服务保障
     * */
    public function serviceGuarantee()
    {
        if (Request()->isPost()) {
            $service_guarantee = Request()->param('service_guarantee');

            $res = Db::name('goods_service_guarantee')->where(' 1 = 1 ')->setField(['service_guarantee' => $service_guarantee]);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $service_guarantee = Db::name('goods_service_guarantee')->value('service_guarantee');

            $this->assign('service_guarantee', json_decode($service_guarantee, true));
            $this->assign('title', '服务保障');

            return $this->view->fetch();
        }
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $one_type_id = $input['one_type_id'];
        $two_type_id = $input['two_type_id'];
        $is_stock = $input['is_stock'];
        $brand_id = $input['brand_id'];

        if ($one_type_id) $where['one_type_id'] = $one_type_id;
        if ($two_type_id) $where['two_type_id'] = $two_type_id;
        if ($brand_id) $where['brand_id'] = $brand_id;

        if ($is_stock == 1) {
            $stock = C('STOCK_WARNING');
            $goods_ids = Db("sku_value")->where(["stock" => ['lt', $stock]])->group("goods_id")->column("goods_id");
            $where['id'] = ['in', $goods_ids];
        }

        $list = Db::name('goods')->where($where)->order('create_time desc')->paginate()->each(
            function ($item) {
                $item['one_type_name'] = Db::name('goods_type')->where(['id' => $item['one_type_id']])->value('name');
                $item['two_type_name'] = Db::name('goods_type')->where(['id' => $item['two_type_id']])->value('name');
                if ($item['upper'] == 1) {
                    $upper_txt = "上架";
                } else {
                    $upper_txt = "下架";
                }
                $item['brand_name'] = Db::name('goods_brand')->where(['id' => $item['brand_id']])->value('name');
                $item['upper_txt'] = $upper_txt;

                return $item;
            }
        );

        $type_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => 0])->select();
        if ($type_list) {
            foreach ($type_list as &$v) {
                $son_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => $v['id']])->select();
                $v['son_list'] = $son_list;
            }
        }
        //查询出品牌

        $brand_list = Db::name('goods_brand')->order('sort asc')->select();

        $this->assign('list', $list);

        $this->assign('type_list', $type_list);
        $this->assign('brand_list', $brand_list);
        $this->assign('type_list_json', json_encode($type_list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '商品列表');

        return $this->fetch();
    }

    /**
     * 导出商品
     */
    public function goodsDataToExcel()
    {
        header("Content-type:text/html;charset=utf-8");
        $input = Request()->param();
        $one_type_id = $input['one_type_id'];
        $two_type_id = $input['two_type_id'];
        $is_stock = $input['is_stock'];
        $brand_id = $input['brand_id'];

        if ($one_type_id) $where['b.one_type_id'] = $one_type_id;
        if ($two_type_id) $where['b.two_type_id'] = $two_type_id;
        if ($brand_id) $where['b.brand_id'] = $brand_id;

        $stock = C('STOCK_WARNING');
        if ($is_stock == 1) {
            $where['a.stock'] = ['lt', $stock];
        }


        $goods_list = Db::name('sku_value a')->join("goods b", 'a.goods_id = b.id', "right")
            ->where($where)->order('create_time desc')->select();

        if (!empty($goods_list)) {
            $goods_data = [];
            foreach ($goods_list as $key => $ulv) {
                $goods_data[$key]['goods_name'] = $ulv['name'];

                $one_type_name = Db::name('goods_type')->where(['id' => $ulv['one_type_id']])->value('name');
                $two_type_name = Db::name('goods_type')->where(['id' => $ulv['two_type_id']])->value('name');

                $goods_data[$key]['category'] = $one_type_name . "-" . $two_type_name;

                $goods_data[$key]['min_vip_price'] = $ulv["min_vip_price"];
                $goods_data[$key]['max_vip_price'] = $ulv["max_vip_price"];

                $goods_data[$key]['min_price'] = $ulv["min_price"];
                $goods_data[$key]['max_price'] = $ulv["max_price"];

                $goods_data[$key]['sales_count'] = $ulv["sales_count"];

                if ($ulv['upper'] == 1) {
                    $upper_txt = "上架";
                } else {
                    $upper_txt = "下架";
                }
                $goods_data[$key]['upper_txt'] = $upper_txt;


                $suk_value_arr = explode("-", $ulv['sku_id']);
                $suk_name_str = '';
                foreach ($suk_value_arr as $vv) {
                    $sku_info = Db::name("sku")->where(["id" => $vv])->find();
                    $sku_p_info = Db::name("sku")->where(["id" => $sku_info['pid']])->find();
                    $suk_name_str .= $sku_p_info['name'] . ": " . $sku_info['name'] . ".";
                }
                $goods_data[$key]['suk_name_str'] = $suk_name_str;
                $goods_data[$key]['vip_price'] = $ulv['vip_price'];
                $goods_data[$key]['price'] = $ulv['price'];
                $goods_data[$key]['stock'] = $ulv['stock'];

                if ($ulv["stock"] < $stock) {
                    $stock_ok = "是";
                } else {
                    $stock_ok = "否";
                }
                $goods_data[$key]['stock_ok'] = $stock_ok;
            }
        } else {
            $goods_data = [];
        }

        $data = [
            "setTitle" => "商品列表",
            "oneList" => ["商品名称", "商品分类", "最低会员价", "最高会员价", "最低零售价", "最高零售价", "销量", "上下架", "属性值", "会员价", "售价", "库存", "是否预警"],
            "more_list" => $goods_data
        ];

        $array_top = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",];
        Loader::import('phpexcel\PHPExcel', EXTEND_PATH);
        $objPHPExcel = new \PHPExcel();


        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);


        $objPHPExcel->createSheet();
        $objPHPExcel->setActiveSheetIndex(0);

        $objPHPExcel->getActiveSheet()->setTitle($data['setTitle']);
        foreach ($data["oneList"] as $oneKey => $oneVo) {
            $objPHPExcel->getActiveSheet()->setCellValue(($array_top[$oneKey]) . '1', $oneVo);
        }

        foreach ($data["more_list"] as $moreKey => $ult) {
            $i = 0;
            foreach ($ult as $vvKey => $vv) {
                $objPHPExcel->getActiveSheet()->setCellValue(($array_top[$i]) . ($moreKey + 2), convertUTF8($vv));
                $i++;
            }
        }

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename="商品.xls"');
        header("Content-Transfer-Encoding:binary");

        $objWriter->save('php://output');
    }

    /**
     * 上下架商品
     */
    public function upperGoods()
    {
        $input = Request()->param();
        $id = $input['id'];
        $upper = $input['upper'];

        $data['upper'] = $upper;
        $data['update_time'] = time();

        $res = Db::name('goods')->where(['id' => $id])->update($data);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }

    }

    /**
     * 新增/编辑 商品
     * */
    public function doGoods()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            Db::startTrans();
            try {
                //参数处理
                parse_str($input['form'], $form);

                $price_arr = [];
                if ($form['skus']) {
                    foreach ($form['skus'] as $v) {
                        if ($v['status'] == 1) {
                            $vip_price_arr[] = $v['vip_price'];
                            $price_arr[] = $v['price'];
                        }
                    }
                }

                $min_vip_price = min($vip_price_arr);
                $max_vip_price = max($vip_price_arr);
                $min_price = min($price_arr);
                $max_price = max($price_arr);

                $skus = $form['skus'];
                unset($form['skus']);
                $id = $form['id'];
                $gift_id = $form['gift_id'];
                foreach ($gift_id as $vg) {
                    if ($vg == 0) adminReturn(2, '请选择赠品');
                }
                if (count($gift_id) != count(array_unique($gift_id))) adminReturn(2, '请勿选择重复赠品');
                if (count($gift_id) > 0) {
                    $gift_ids = implode(",", $gift_id);
                } else {
                    $gift_ids = "";
                }

                if (empty($form['name'])) adminReturn(2, '请输入商品名称');
                if (empty($form['img'])) adminReturn(2, '请上传封面图');
                //                if (empty($form['poster'])) adminReturn(2, '请上传分享海报');
                if (empty($form['content'])) adminReturn(2, '请输入商品介绍');
                $time = time();
                $data = [
                    'name' => $form['name'],
                    'img' => $form['img'],
                    'poster' => $form['poster'],
                    'imgs' => $form['imgs'],
                    'one_type_id' => $form['one_type_id'],
                    'two_type_id' => $form['two_type_id'] ? : 0,
                    'sales_count' => $form['sales_count'],
                    'skus' => $input['skus'],
                    'upper' => $form['upper'],
                    'brand_id' => $form['brand_id'] ? : 0,
                    'min_vip_price' => 0,
                    'max_vip_price' => 0,
                    'min_price' => $min_price >= 0 ? $min_price : 0,
                    'max_price' => $max_price >= 0 ? $max_price : 0,
                    'product_param' => $form['product_param'] ? $form['product_param'] : '',
                    'user_instructions' => $form['user_instructions'],
                    'desc_imgs' => $form['desc_imgs'],
                    'content' => $form['content'],
                    'gift_ids' => $gift_ids
                ];

                if ($id > 0) {
                    //编辑
                    $data['update_time'] = $time;

                    Db::name('goods')->where(['id' => $id])->update($data);

                    Db::name('sku_value')->where(['goods_id' => $id])->delete();

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    //此行请勿删除
                    cache('sku_' . $id, null);

                    Db::commit();
                    adminReturn(1, '编辑商品成功', url('goodsList'));
                } else {
                    //新增
                    $data['create_time'] = $time;

                    $goods_id = Db::name('goods')->insertGetId($data);

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $goods_id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    Db::commit();
                    adminReturn(1, '新增商品成功', url('goodsList'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~' . $e);
            }
        } else {
            $id = Request()->param('id');

            $info = Db::name('goods')->where(['id' => $id])->find();
            $info['imgs_arr'] = doImgs($info['imgs']);
            $info['desc_imgs_arr'] = doImgs($info['desc_imgs']);
            $info['product_param'] = json_decode($info['product_param'], true);
            if ($info["gift_ids"]) {
                $gifts = explode(",", $info["gift_ids"]);
                foreach ($gifts as $key => &$vg) {
                    $is_de = Db::name("goods_gift")->where(["id" => $vg])->value("is_del");
                    if ($is_de == 1) {
                        array_splice($gifts, $key, 1);
                    }
                }
                $info["gift_arr"] = $gifts;
            } else {
                $info["gift_arr"] = [];
            }

            $type_list = Db::name('goods_type')->field('id,name')->where(['pid' => 0])->select();
            if ($type_list) {
                foreach ($type_list as &$v) {
                    $son_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => $v['id']])->select();
                    $v['son_list'] = $son_list;
                }
            } else {
                $type_list = [];
            }

            $sku_list = Db::name('sku')->field('id,name title')->where(['pid' => 0])->select();
            if ($sku_list) {
                //$skus_id_arr：所有属性的id集合
                $skus_id_arr = [];

                foreach ($sku_list as &$v) {
                    if ($id > 0) {
                        $sku_value_list = Db::name('sku_value')->field('sku_id,stock')->where(['goods_id' => $id])->select();

                        $skus = json_decode($info['skus'], true);
                        if ($sku_value_list) {
                            foreach ($sku_value_list as &$val) {
                                if ($skus) {
                                    $skus['skus[' . $val['sku_id'] . '][stock]'] = $val['stock'];
                                }

                                $sku_id = explode('-', $val['sku_id']);
                                if ($sku_id) {
                                    foreach ($sku_id as &$value) {
                                        if (!in_array($value, $skus_id_arr)) {
                                            $skus_id_arr[] = $value;
                                        }
                                    }
                                }
                            }
                        }
                        $json_skus = json_encode($skus, JSON_UNESCAPED_UNICODE);
                        Db::name('goods')->where(['id' => $id])->setField('skus', $json_skus);

                        $info['skus'] = $json_skus;

                        $parent_list = Db::name('sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr]])->select();
                        $parent_ids = array_column($parent_list, 'pid');

                        $v['checked'] = false;
                        if (in_array($v['id'], $parent_ids)) $v['checked'] = true;
                    } else {
                        $v['checked'] = false;
                    }

                    $child = Db::name('sku')->field('id,name title')->where(['pid' => $v['id']])->select();
                    if ($child) {
                        foreach ($child as &$val) {
                            $val['checked'] = in_array($val['id'], $skus_id_arr) ? true : false;
                        }
                    }
                    $v['child'] = $child;
                }
            }

            //查询出赠送商品
            $gift_list = Db::name("goods_gift")->field("id,gift_name,gift_price")->where(["is_del" => 0])->select();
            $this->assign('title', $id ? '编辑商品' : '新增商品');

            //查询出品牌

            $brand_list = Db::name('goods_brand')->order('sort asc')->select();

            $this->assign('info', $info);
            $this->assign('type_list', $type_list);
            $this->assign('type_list_json', json_encode($type_list, JSON_UNESCAPED_UNICODE));
            $this->assign('sku_list', json_encode($sku_list, JSON_UNESCAPED_UNICODE));
            $this->assign('gift_list', $gift_list);
            $this->assign('brand_list', $brand_list);
            $this->assign('gift_list_json', json_encode($gift_list, JSON_UNESCAPED_UNICODE));

            return $this->fetch();
        }
    }

    /**
     * 删除商品
     * */
    public function delGoods()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '商品ID缺失');

        $info = Db::name('goods')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('goods')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * banner列表
     */
    public function bannerList()
    {
        $list = Db::name('banner')->paginate();

        $this->assign('list', $list);
        $this->assign('title', 'banner列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 banner
     * */
    public function doBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $type = $input["type"];
            $to_id = $input["to_id"];

            if (empty($img)) adminReturn(2, '请上传banner图');

            $data = [
                "img" => $img,
                "type" => $type,
                'to_id' => $to_id
            ];

            if ($id > 0) {
                $res = Db::name('banner')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '编辑banner失败或未编辑');
                }
            } else {
                $res = Db::name('banner')->insert($data);
                if ($res) {
                    adminReturn(1, '新增banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '新增banner失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('banner')->where(['id' => $id])->find();

            $goods_list = Db::name('goods')->field('id,name')->select();
            $this->assign('goods_list', $goods_list);
            $this->assign('goods_list_obj', json_encode($goods_list, JSON_UNESCAPED_UNICODE));

            $article_list = Db::name('article')->field('id,title name')->select();
            $this->assign('article_list_obj', json_encode($article_list, JSON_UNESCAPED_UNICODE));

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . 'banner');

            return $this->view->fetch();
        }
    }

    /**
     * 删除banner
     * */
    public function delBanner()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'bannerID缺失');

        $info = Db::name('banner')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('banner')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 门店区域列表
     * */
    public function shopRegionList()
    {
        $list = Db::name('shop_region')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '门店区域列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 门店区域
     * */
    public function doShopRegion()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $province_id = $input["province_id"];
            $city_id = $input["city_id"];
            $area_id = $input["area_id"];

            if (empty($province_id)) adminReturn(2, "请选择省");
            if (empty($city_id)) adminReturn(2, "请选择市");
            if (empty($area_id)) adminReturn(2, "请选择区");

            $province = getProvinceName($province_id);
            $city = getCityName($city_id);
            $area = getAreaName($area_id);

            $data = [
                "province" => $province,
                "city" => $city,
                "area" => $area,
            ];

            $where['province'] = $province;
            $where['city'] = $city;
            $where['area'] = $area;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('shop_region')->where($where)->count();
            if ($count) apiReturn(2, '该区域已存在，请重新输入');

            if ($id > 0) {
                $data['update_time'] = time();
                $res = Db::name('shop_region')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑门店区域成功', url('shopRegionList'));
                } else {
                    adminReturn(2, '编辑门店区域失败或未编辑');
                }
            } else {
                $data['create_time'] = time();
                $res = Db::name('shop_region')->insert($data);
                if ($res) {
                    adminReturn(1, '新增门店区域成功', url('shopRegionList'));
                } else {
                    adminReturn(2, '新增门店区域失败');
                }
            }
        } else {
            $id = Request()->param('id');

            $region_list = Db::name('province')->field('province_id id,name')->order('sid asc')->select();
            foreach ($region_list as &$v) {
                $city_list = Db::name('city')->field('city_id id,name')->where(['province_id' => $v['id']])->order('sid asc')->select();
                foreach ($city_list as &$val) {
                    $area_list = Db::name('area')->field('area_id id,name')->where(['city_id' => $val['id']])->order('sid asc')->select();
                    $val['area_list'] = $area_list;
                }
                $v['city_list'] = $city_list;
            }
            $this->assign('region_list', $region_list);
            $this->assign('region_list_json', json_encode($region_list, JSON_UNESCAPED_UNICODE));

            if ($id) {
                $info = Db::name('shop_region')->where(['id' => $id])->find();
                $info['province_id'] = getProvinceId($info['province']);
                $info['city_id'] = getCityId($info['province'], $info['city']);
                $info['area_id'] = getAreaId($info['province'], $info['city'], $info['area']);
            }

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '门店区域');

            return $this->view->fetch();
        }
    }

    /**
     * 删除门店区域
     * */
    public function delShopRegion()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '门店区域ID缺失');

        $info = Db::name('shop_region')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('shop_region')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 门店列表
     * */
    public function shopList()
    {
        $input = Request()->param();

        $status = $input['status'];

        if ($status > -1) $where['status'] = $status;

        $list = Db::name('shop')->where($where)->paginate()->each(function ($val) {
            $user_info = Db::name('user')->field('username,mobile')->where(['id' => $val['user_id']])->find();
            $val['username'] = $user_info['username'];
            $val['mobile'] = $user_info['mobile'];

            switch ($val['status']) {
                case 0:
                    $status_desc = '待审核';
                    break;
                case 1:
                    $status_desc = '审核成功';
                    break;
                case 2:
                    $status_desc = '审核失败';
                    break;
            }
            $val['status_desc'] = $status_desc;

            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', '门店列表');

        return $this->view->fetch();
    }

    /**
     * 门店详情
     * */
    public function doShop()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, '门店ID缺失');

        $info = Db::name('shop')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                if (Request()->isPost()) {
                    $time = time();
                    $data = [
                        'status' => $input['status'],
                        'update_time' => $time
                    ];
                    if ($input['status'] == 1) $data['success_time'] = $time;

                    Db::name('shop')->where(['id' => $id])->update($data);

                    Db::commit();
                    adminReturn(1, '操作成功');
                } else {
                    $info['shop_imgs'] = doImgs($info['shop_imgs']);

                    $this->assign('info', $info);

                    $this->assign('title', '门店详情');
                    return $this->view->fetch();
                }
            } catch (\Exception $e) {
                adminReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            adminReturn(2, '门店不存在或已删除');
        }
    }

    /**
     * 门店 禁用/启用
     * */
    public function doDisable()
    {
        $input = Request()->param();

        $id = $input['id'];
        $disable = $input['disable'];

        if (empty($id)) adminReturn(2, '门店ID缺失');

        $res = Db::name('shop')->where(['id' => $id])->setField('disable', $disable);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }


    /**
     * 关于我们
     * */
    public function doAboutUs()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            if (empty($content)) apiReturn(2, '请输入内容');

            $res = Db::name('about_us')->where(['id' => 1])->setField('content', $content);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $content = Db::name('about_us')->where(['id' => 1])->value('content');
            $this->assign('content', $content);

            $this->assign('title', '关于我们');
            return $this->view->fetch();
        }
    }

    /**
     * 折扣券设置
     */
    public function couponList()
    {
        $input = Request()->param();

        $name = $input['name'];
        $where["id"] = ["gt", 0];
        if ($name) $where['name'] = ["like", '%' . $name . '%'];
        $list = Db::name('coupon')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '折扣券列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 优惠券
     * */
    public function doCoupon()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input["id"];
            $name = $input["name"];
            $full_price = $input["full_price"];
            $face_price = $input["face_price"];
            $use_day = $input["use_day"];


            if (empty($name)) adminReturn(2, "请输入券名称");
            if (empty($full_price)) adminReturn(2, "请输入消费到达金额");
            if (empty($face_price)) adminReturn(2, "请输入面值");
            if (empty($use_day)) adminReturn(2, "请输入有效期（天）");

            if ($full_price < 0) adminReturn(2, "消费到达金额不能小于0");
            if ($face_price < 0) adminReturn(2, "面值不能小于0");
            if ($use_day < 0) adminReturn(2, "有效期不能小于0");
            if ($full_price < $face_price) adminReturn(2, "消费到达金额不能小于面值");
            if (!preg_match("/^[1-9][0-9]*$/", $use_day)) adminReturn(2, "有效期只能是正整数");

            $data = [
                "name" => $name,
                "full_price" => $full_price,
                "face_price" => $face_price,
                "use_day" => $use_day,
            ];

            if ($id > 0) {
                $res = Db::name('coupon')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑优惠券成功', url('couponList'));
                } else {
                    adminReturn(2, '编辑优惠券失败或未编辑');
                }
            } else {
                $data["create_time"] = time();
                $res = Db::name('coupon')->insert($data);
                if ($res) {
                    adminReturn(1, '新增优惠券成功', url('couponList'));
                } else {
                    adminReturn(2, '新增优惠券失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('coupon')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '优惠券');

            return $this->view->fetch();
        }
    }

    /**
     *删除优惠券
     */
    public function delCoupon()
    {
        $id = Request()->param('id');
        if (empty($id)) adminReturn(2, '参数丢失');
        $res_de_coupon = Db::name('coupon')->where(['id' => $id])->delete();
        if ($res_de_coupon) {
            adminReturn(1, '删除优惠券成功', url('deCoupon'));
        } else {
            adminReturn(2, '删除优惠券失败',);
        }
    }

    /**
     *分发优惠券
     */
    public function distributeCoupon()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $user_ids = $input['user_id'];
            if (empty($id)) adminReturn(2, '参数丢失');
            if (count($user_ids) < 1) adminReturn(2, '请勾选用户');
            $coupon_info = Db::name("coupon")->where(["id" => $id])->find();

            $data = [];
            foreach ($user_ids as $key => $vo) {
                $expire_time = time() + $coupon_info['use_day'] * 24 * 3600;
                $data[] = [
                    "user_id" => $vo,
                    "coupon_name" => $coupon_info['name'],
                    "full_price" => $coupon_info['full_price'],
                    "face_price" => $coupon_info['face_price'],
                    "expire_time" => date("Y-m-d", $expire_time),
                    "status" => 1,
                    "update_time" => time(),
                    "create_time" => time(),
                ];
            }
            $res = Db::name('user_coupon')->insertAll($data);
            if ($res) {
                adminReturn(1, '发放优惠券成功', url('userCoupon'));
            } else {
                adminReturn(2, '发放优惠券失败');
            }
        } else {
            $id = Request()->param('id');
            $name = Request()->param('name');
            if (empty($id)) adminReturn(2, '参数丢失');
            $map['status'] = 1;
            $map['id'] = ['gt', 1];
            if (!empty($name)) $map['username'] = ['like', "%" . $name . "%"];
            $user_list = Db::name("user")->where($map)->select();

            $this->assign('id', $id);
            $this->assign('user_list', $user_list);
            $this->assign('title', '发送优惠券');
            return $this->view->fetch();
        }
    }

    /**
     * 优惠券发放记录
     */
    public function userCoupon()
    {
        $input = Request()->param();

        $name = $input['name'];

        if ($name) $where['b.username'] = ["like", '%' . $name . '%'];

        $user_ids = '';
        $list = Db::name('user_coupon a')->field("a.*,b.id,b.username")->join("shop_user b", "a.user_id = b.id", "left")
            ->where($where)->order('a.create_time desc')->paginate()->each(
                function ($v) {
                    if ($v['status'] == 1) {
                        $status_txt = '待使用';
                    } elseif ($v['status'] == 2) {
                        $status_txt = '已使用';
                    } elseif ($v['status'] == 3) {
                        $status_txt = '已过期';
                    } else {
                        $status_txt = "";
                    }
                    $v["status_txt"] = $status_txt;

                    return $v;
                }
            );
        $sum_full_price = Db::name('user_coupon a')->join('shop_user b', 'a.user_id = b.id', 'left')->where($where)->sum('full_price');
        $this->assign('list', $list);
        $this->assign('sum_full_price', $sum_full_price);

        $this->assign('title', '发放记录');

        return $this->fetch();
    }

    /**
     * 收回
     */
    public function deUserCoupon()
    {
        $input = Request()->param();
        $id = $input['id'];
        if (empty($id)) adminReturn(2, '参数丢失');
        $res_de_coupon = Db::name('user_coupon')->where(['id' => $id])->delete();
        if ($res_de_coupon) {
            adminReturn(1, '删除成功', url('userCoupon'));
        } else {
            adminReturn(2, '删除失败',);
        }
    }

    /**
     * 公告列表
     */
    public function msgList()
    {
        $input = Request()->param();

        $title = $input['title'];
        $where["type"] = 3;
        if ($title) $where['title'] = ["like", '%' . $title . '%'];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 公告
     */
    public function doMsg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $title = $input["title"];
            $content = $input["content"];

            if (empty($title)) adminReturn(2, "请输入标题");
            if (empty($content)) adminReturn(2, "请填写公告内容");

            if ($id) {
                $data = [
                    'title' => $title,
                    'content' => $content
                ];

                $res = Db::name('msg')->where(['id' => $id])->update($data);
            } else {
                $data = [
                    "user_id" => 0,
                    "title" => $title,
                    "content" => $content,
                    "type" => 3,
                    "look_count" => 0,
                    "create_time" => time()
                ];

                $res = Db::name('msg')->insert($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '公告成功', url('msgList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '公告失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('msg')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '公告详情' : '新增公告'));

            return $this->view->fetch();
        }
    }

    /**
     * 删除公告
     */
    public function delMsg()
    {
        $input = Request()->param();

        $id = $input["id"];

        if ($id > 0) {
            $res = Db::name('msg')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除公告成功', url('msgList'));
            } else {
                adminReturn(2, '删除公告失败');
            }
        }
    }

    /**
     *　意见反馈
     */
    public function feedbackList()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $where["a.id"] = ["gt", "0"];

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('feedback a')->field("a.*,b.username")->join('user b', "a.user_id = b.id", "left")
            ->where($where)->order('a.create_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '意见反馈列表');

        return $this->fetch();
    }

    /**
     *会员管理
     */
    public function userList()
    {
        $input = Request()->param();

        $username = $input['username'];
        $mobile = $input['mobile'];
        $level = $input['level'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($username)) $where["username"] = ["like", "%" . $username . "%"];
        if (!empty($mobile)) $where["mobile"] = ["like", "%" . $mobile . "%"];
        if (!empty($level)) {
            $where["level"] = $level;
        } else {
            $where['level'] = ['gt', 0];
        }

        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }
        $list = Db::name('user')->where($where)->order('create_time desc')->paginate()->each(
            function ($v) {
                if ($v['status'] == 1) {
                    $status_txt = '正常';
                } elseif ($v['status'] == 2) {
                    $status_txt = '禁用';
                } elseif ($v['status'] == 3) {
                    $status_txt = '激活';
                } else {
                    $status_txt = "";
                }
                $v["status_txt"] = $status_txt;
                $address_info = Db::name("address")->field("province_id,city_id,area_id")->where(["user_id" => $v['id'], 'is_default' => 1])->find();
                if ($address_info) {
                    $province = Db::name('province')->where(['province_id' => $address_info['province_id']])->value('name');
                    $city = Db::name('city')->where(['city_id' => $address_info['city_id']])->value('name');
                    $area = Db::name('area')->where(['area_id' => $address_info['area_id']])->value('name');
                    $v['address'] = $province . "-" . $city . "-" . $area;
                } else {
                    $v['address'] = '';
                }


                if ($v['gender'] == 0) {
                    $v['gender_txt'] = "保密";
                } elseif ($v['gender'] == 1) {
                    $v['gender_txt'] = "男";
                } else {
                    $v['gender_txt'] = "女";
                }
                if ($v['level'] == 1) {
                    $v['level_txt'] = "游客";
                } elseif ($v['level'] == 2) {
                    $v['level_txt'] = "VIP";
                } elseif ($v['level'] == 3) {
                    $v['level_txt'] = "社区服务站";
                } elseif ($v['level'] == 4) {
                    $v['level_txt'] = "县区服务站";
                } else {
                    $v['level_txt'] = "城市服务站";
                }
                if ($v['up_user_id'] > 0) {
                    $v['up_username'] = Db::name("user")->where(["id" => $v['up_user_id']])->value("username");
                } else {
                    $v['up_username'] = "";
                }

                $share_count = Db("user")->where(["up_user_id" => $v['id']])->count();
                if (empty($share_count)) {
                    $share_count = 0;
                }
                $v['share_count'] = $share_count;

                // 自己消费总额
                $me_all_consume = Db::name('order')->where(['user_id' => $v['id'], 'is_pay' => 1, 'complete_time' => ['neq', 0]])->sum('pay_price');
                $me_all_consume = sprintf('%.2f', $me_all_consume);
                // 消费金额
                $all_consume = $me_all_consume + action('Algorithm/Algorithm/allConsume', ['user_id' => $v['id']]);
                $v['all_consume'] = sprintf('%.2f', $all_consume);

                // 冻结收益
                $frozen_profit = Db::name('profit')->where(['user_id' => $v['id'], 'status' => 1])->sum('price');
                $v['frozen_profit'] = sprintf('%.2f', $frozen_profit);

                return $v;
            }
        );
        $this->assign('list', $list);

        $this->assign('title', '信息管理');

        return $this->fetch();
    }

    /**
     * 会员通讯录
     */
    public function shareUserList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        $list = Db::name('user')->field('id,username,avatar,mobile,is_activation,create_time')->where(['up_user_id' => $user_id])->order('create_time desc')->paginate()->each(
            function ($v) {
                $v['avatar'] = doAvatar($v['avatar']);
                return $v;
            }
        );

        $this->assign('list', $list);

        $this->assign('title', '会员通讯录');
        return $this->fetch();
    }

    /**
     * 收益变更
     * */
    public function profitChange()
    {
        $input = Request()->param();

        $id = $input['id'];
        $type = $input['type'];
        $price = $input['price'];
        $reason = $input['reason'];

        if (empty($id)) adminReturn(2, '用户ID缺失');
        if (empty($type)) adminReturn(2, '请选择变更类型');
        if (empty($price) || $price <= 0) adminReturn(2, '请输入正确的变更金额');
        if (empty($reason)) adminReturn(2, '请输入变更原因');

        Db::startTrans();
        try {
            $time = time();
            $old_profit = Db::name('user')->where(['id' => $id])->value('all_profit');
            $do_user_id = cookie('id');
            // 新增收益变更记录
            $data = [
                'do_user_id' => $do_user_id,
                'user_id' => $id,
                'type' => $type,
                'old_profit' => $old_profit,
                'price' => $price,
                'reason' => $reason,
                'create_time' => $time
            ];
            Db::name('profit_change')->insert($data);

            $profit_type = $type == 1 ? 10 : 11;

            // 新增收益记录
            $profit_data = [
                'user_id' => $id,
                'price' => $price,
                'type' => $profit_type,
                'remark' => $reason,
                'status' => 2,
                'create_time' => $time
            ];
            Db::name('profit')->insert($profit_data);

            // 变更用户收益
            if ($type == 1)
                Db::name('user')->where(['id' => $id])->setInc('all_profit', $price);
            else
                Db::name('user')->where(['id' => $id])->setDec('all_profit', $price);

            if ($profit_type == 10) {
                // 充值收益
                $first_value = '您好，您的充值已完成';
                $keyword1_value = '充值通知';
            } else if ($profit_type == 11) {
                // 处罚收益
                $first_value = '您好，根据相关规定对您扣款执行完毕！';
                $keyword1_value = '扣款通知';
                $price = '-' . $price;
            }

            // 发送微信公众号模板消息
            $template_msg = [
                'first' => [
                    'value' => $first_value,
                    'color' => '#743A3A'
                ],
                'keyword1' => [
                    'value' => $keyword1_value,
                    'color' => '#743A3A'
                ],
                'keyword2' => [
                    'value' => $price,
                    'color' => '#743A3A'
                ],
                'keyword3' => [
                    'value' => date('Y-m-d'),
                    'color' => '#743A3A'
                ],
                'keyword4' => [
                    'value' => '点击查看',
                    'color' => '#743A3A'
                ],
                'remark' => [
                    'value' => $reason,
                    'color' => '#743A3A'
                ]
            ];

            $user_info = Db::name('user')->field('mobile,gzh_openid')->where(['id' => $id])->find();

            $gzh_openid = $user_info['gzh_openid'];
            $mobile = $user_info['mobile'];
            $page = 'pages/my_income/my_income';

            if ($gzh_openid) sendWxTemplateNotice($gzh_openid, $template_msg, $profit_type, $page);

            Db::commit();
            adminReturn(1, '变更收益成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试' . $e);
        }
    }

    /**
     * 级别变更
     * */
    public function levelChange()
    {
        $input = Request()->param();

        $id = $input['id'];
        $level = $input['level'];
        $reason = $input['reason'];

        if (empty($id)) adminReturn(2, '用户ID缺失');
        if (empty($level)) adminReturn(2, '请选择变更级别');
        if (empty($reason)) adminReturn(2, '请输入变更原因');

        Db::startTrans();
        try {
            $time = time();

            $old_level = Db::name('user')->where(['id' => $id])->value('level');
            $do_user_id = cookie('id');
            $data = [
                'do_user_id' => $do_user_id,
                'user_id' => $id,
                'old_level' => $old_level,
                'level' => $level,
                'reason' => $reason,
                'create_time' => $time
            ];
            Db::name('level_change')->insert($data);

            $user_data = [
                'level' => $level,
                'update_time' => $time
            ];
            if ($old_level != $level) $user_data['is_change_level'] = 1;

            Db::name('user')->where(['id' => $id])->update($user_data);

            // 某个用户的级别变更需要将其所有上级都加入到用户升级的任务计划
            addAllUpUserToUpPlan($id);

            Db::commit();
            adminReturn(1, '变更级别成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**
     * 收益汇总
     * */
    public function profitSummaryList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (empty($user_id)) apiReturn(2, '用户ID缺失');

        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $where['user_id'] = $user_id;
        $where['type'] = ['IN', [1, 2, 3, 4, 5, 6, 7, 9, 10, 11]];
        $where['status'] = ['neq', -1];

        $select_list = Db::name('profit')->distinct(true)->field('user_id,FROM_UNIXTIME(create_time, "%Y-%m-%d") date')->where($where)->select();
        $count = count($select_list);

        $list = Db::name('profit')->distinct(true)->field('user_id,FROM_UNIXTIME(create_time, "%Y-%m-%d") date')->where($where)->order('create_time desc')->paginate(Config('paginate.list_rows'), $count)->each(function ($v) {
            $start_time = strtotime($v['date']);
            $end_time = $start_time + 60 * 60 * 24 - 1;

            $each_where['user_id'] = $v['user_id'];
            $each_where['create_time'] = ['between', [$start_time, $end_time]];
            $each_where['status'] = ['neq', -1];

            // 个人所获收益总额统计
            $all_get_profit = Db::name('profit')->where($each_where)->where(['type' => ['IN', [1, 2, 3, 6, 7, 9]]])->sum('price');
            $v['all_get_profit'] = sprintf('%.2f', $all_get_profit);
            // 成功提现总额
            $all_withdraw_profit = Db::name('profit')->where($each_where)->where(['type' => 5])->sum('price');
            $v['all_withdraw_profit'] = sprintf('%.2f', $all_withdraw_profit);
            // 充值总金额
            $all_recharge_profit = Db::name('profit')->where($each_where)->where(['type' => 10])->sum('price');
            $v['all_recharge_profit'] = sprintf('%.2f', $all_recharge_profit);
            // 使用收益购物总金额
            $all_buy_profit = Db::name('profit')->where($each_where)->where(['type' => 4])->sum('price');
            $v['all_buy_profit'] = sprintf('%.2f', $all_buy_profit);
            // 扣款总额
            $all_deduct_profit = Db::name('profit')->where($each_where)->where(['type' => 11])->sum('price');
            $v['all_deduct_profit'] = sprintf('%.2f', $all_deduct_profit);

            return $v;
        });

        $this->assign('list', $list);

        $all_list = Db::name('profit')->distinct(true)->field('user_id,FROM_UNIXTIME(create_time, "%Y-%m-%d") date')->where($where)->order('create_time desc')->select();
        if ($all_list) {
            $all_start_date = '';
            $all_end_date = '';
            foreach ($all_list as $k => &$v) {
                if ($k == 0) {
                    $all_end_date = $v['date'];
                } else if ($k + 1 == count($all_list)) {
                    $all_start_date = $v['date'];
                }

                $start_time = strtotime($v['date']);
                $end_time = $start_time + 60 * 60 * 24 - 1;

                $each_where['user_id'] = $v['user_id'];
                $each_where['create_time'] = ['between', [$start_time, $end_time]];
                $each_where['status'] = ['neq', -1];

                // 个人所获收益总额统计
                $all_get_profit = Db::name('profit')->where($each_where)->where(['type' => ['IN', [1, 2, 3, 6, 7, 9]]])->sum('price');
                $v['all_get_profit'] = sprintf('%.2f', $all_get_profit);
                // 成功提现总额
                $all_withdraw_profit = Db::name('profit')->where($each_where)->where(['type' => 5])->sum('price');
                $v['all_withdraw_profit'] = sprintf('%.2f', $all_withdraw_profit);
                // 充值总金额
                $all_recharge_profit = Db::name('profit')->where($each_where)->where(['type' => 10])->sum('price');
                $v['all_recharge_profit'] = sprintf('%.2f', $all_recharge_profit);
                // 使用收益购物总金额
                $all_buy_profit = Db::name('profit')->where($each_where)->where(['type' => 4])->sum('price');
                $v['all_buy_profit'] = sprintf('%.2f', $all_buy_profit);
                // 扣款总额
                $all_deduct_profit = Db::name('profit')->where($each_where)->where(['type' => 11])->sum('price');
                $v['all_deduct_profit'] = sprintf('%.2f', $all_deduct_profit);
            }
        }

        $census = [
            'range_date' => ($input['start_time'] ? : $all_start_date) . ' - ' . ($input['end_time'] ? : $all_end_date),
            'all_get_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_get_profit'))) : '0.00',
            'all_withdraw_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_withdraw_profit'))) : '0.00',
            'all_recharge_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_recharge_profit'))) : '0.00',
            'all_buy_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_buy_profit'))) : '0.00',
            'all_deduct_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_deduct_profit'))) : '0.00',
        ];
        $this->assign('census', $census);

        $this->assign('title', '收益汇总');
        return $this->view->fetch();
    }

    /**
     *会员详情
     */
    public function doUser()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $gender = $input["gender"];
            $mobile = $input["mobile"];
            $level = $input["level"];
            $status = $input["status"];
            $real_name = $input["real_name"];
            $back_num = $input["back_num"];

            if ($gender) $data['gender'] = $gender;
            if ($mobile) $data['mobile'] = $mobile;
            if ($level) $data['level'] = $level;
            if ($status) $data['status'] = $status;
            if ($real_name) $data['real_name'] = $real_name;
            if ($back_num) $data['back_num'] = $back_num;

            $data["update_time"] = time();
            $res = Db::name('user')->where(["id" => $id])->update($data);
            if ($res) {
                adminReturn(1, '修改成功', url('userList'));
            } else {
                adminReturn(2, '修改失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('user')->where(['id' => $id])->find();
                $address_info = Db::name("address")->field("province_id,city_id,area_id")->where(["user_id" => $id, 'is_default' => 1])->find();
                if ($address_info) {
                    $province = Db::name('province')->where(['province_id' => $address_info['province_id']])->value('name');
                    $city = Db::name('city')->where(['city_id' => $address_info['city_id']])->value('name');
                    $area = Db::name('area')->where(['area_id' => $address_info['area_id']])->value('name');
                    $info['address'] = $province . "-" . $city . "-" . $area;
                } else {
                    $info['address'] = "";
                }

                $info['avatar'] = doAvatar($info['avatar']);
                $share_count = Db("user")->where(["up_user_id" => $info['id']])->count();
                if (empty($share_count)) {
                    $share_count = 0;
                }
                $info['share_count'] = $share_count;
                if ($info['up_user_id'] > 0) {
                    $info['up_username'] = Db::name("user")->where(["id" => $info['up_user_id']])->value("username");
                } else {
                    $info['up_username'] = "";
                }

                $finance_info = $this->censusUserProfit($id);
                $info['finance_info'] = $finance_info;
            }

            $this->assign('info', $info);
            $this->assign('title', '用户详情');

            return $this->view->fetch();
        }
    }

    /**
     * 统计用户财务情况
     * */
    public function censusUserProfit($info_user_id = 0)
    {
        $input = Request()->param();

        $user_id = $info_user_id ? : $input['user_id'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if ($user_id) $where['user_id'] = $user_id;
        if (!empty($start_time) && empty($end_time)) {
            $all_consume_where["complete_time"] = ["egt", strtotime($start_time)];
            $all_withdraw_where["create_time"] = ["egt", strtotime($start_time)];
            $all_recharge_where['create_time'] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $all_consume_where["complete_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
            $all_withdraw_where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
            $all_recharge_where['create_time'] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $all_consume_where["complete_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
            $all_withdraw_where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
            $all_recharge_where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $me_all_consume = Db::name('order')->where(['user_id' => $user_id, 'is_pay' => 1, 'complete_time' => ['neq', 0]])->sum('pay_price');

        // 总累计销售额 = 自己消费总额 + 我的所有下线的消费统计
        $all_consume = $me_all_consume + action('Algorithm/Algorithm/allConsume', ['user_id' => $user_id]);


        // 所有可用收益统计（总累计收益）
        //        $all_profit = Db::name('profit')->where($where)->where([])
        $all_profit = 0;

        // 总提现额统计
        $all_withdraw = Db::name('withdrawal')->where($where)->where($all_withdraw_where)->sum('real_price');

        // 充值总金额
        $all_recharge = Db::name('profit_change')->where($where)->where($all_recharge_where)->where(['type' => 1])->sum('price');

        $data = [
            'all_consume' => sprintf("%.2f", $all_consume),
            'all_profit' => sprintf("%.2f", $all_profit),
            'all_withdraw' => sprintf("%.2f", $all_withdraw),
            'all_recharge' => sprintf("%.2f", $all_recharge),
        ];

        if ($info_user_id !== 0) {
            return $data;
        } else {
            apiReturn(1, '获取数据成功', $data);
        }
    }

    /**
     * 修改用户状态
     */
    public function statusUser()
    {
        $input = Request()->param();
        $id = $input['id'];
        $status = $input['status'];

        $data['status'] = $status;
        $data['update_time'] = time();

        $res = Db::name('user')->where(['id' => $id])->update($data);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }

    }

    /**
     * 会员收益明细
     * */
    public function userProfitList()
    {
        $user_id = Request()->param('id');

        if (empty($user_id)) adminReturn(2, '会员ID缺失');

        $profit_where = [
            'user_id' => $user_id,
            'status' => ['neq', -1]
        ];
        $list = Db::name('profit')->field('id,order_id,user_id,type,price,remark,create_time')->where($profit_where)->order('create_time desc')->paginate()->each(
            function ($v) {
                if ($v['type'] == 1 || $v['type'] == 2 || $v['type'] == 3) {
                    $pay_user_id = Db::name('order')->where(['id' => $v['order_id']])->value('user_id');
                    if ($pay_user_id) {
                        $user_info = Db::name('user')->field('username,gender')->where(['id' => $pay_user_id])->find();
                        $username = $user_info['username'];
                        //                        if (mb_strlen($username) > 6) $username = cutSubstr($username, 6);
                    }
                } else {
                    $username = '';
                }

                switch ($v['type']) {
                    case 2:
                    case 1:
                        $desc = ' 成功购买了商品';
                        $change = 'plus';
                        break;
                    case 3:
                        $desc = '消费，您获得服务津贴';
                        $change = 'plus';
                        break;
                    case 4:
                        $desc = '购物收益抵扣';
                        $change = 'minus';
                        break;
                    case 5:
                        $desc = '收益提现';
                        $change = 'minus';
                        break;
                    case 6:
                    case 7:
                    case 9:
                        $desc = $v['remark'];
                        $change = 'plus';
                        break;
                    case 8:
                        $desc = '收益提现审核失败，收益返还';
                        $change = 'plus';
                        break;
                    case 10:
                        $desc = '充值收益';
                        $change = 'plus';
                        break;
                    case 11:
                        $desc = '处罚收益';
                        $change = 'minus';
                        break;
                    case 12:
                        $desc = '购物抵扣收益退款';
                        $change = 'plus';
                        break;
                }

                $v['username'] = $username;
                $v['desc'] = $desc;
                $v['change'] = $change;

                $v['create_time'] = timeFormat($v['create_time']);

                return $v;
            }
        );
        $this->assign('list', $list);

        $this->assign('title', '会员收益明细');

        return $this->fetch();
    }

    /**
     * 收益变更记录
     * */
    public function profitChangeList()
    {
        $input = Request()->param();

        $username = $input['username'];
        $mobile = $input['mobile'];
        $type = $input['type'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($username)) $where["u.username"] = ["like", "%" . $username . "%"];
        if (!empty($mobile)) $where["u.mobile"] = ["like", "%" . $mobile . "%"];
        if (!empty($type)) $where['p.type'] = $type;

        if (!empty($start_time) && empty($end_time)) {
            $where["p.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["p.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["p.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('profit_change p')->join('shop_user u', 'p.user_id = u.id', 'left')
            ->field('p.user_id,p.do_user_id,u.username,u.mobile,p.type,p.old_profit,p.price,p.reason,p.create_time')
            ->where($where)
            ->order('p.create_time desc')
            ->paginate()->each(function ($val) {
                $username = Db::name('user')->where(['id' => $val['user_id']])->value('username');
                $val['username'] = $username;
                $do_username = Db::name('user')->where(['id' => $val['do_user_id']])->value('username');
                $val['do_username'] = $do_username;

                return $val;
            });
        $this->assign('list', $list);

        $this->assign('title', '收益变更记录');
        return $this->view->fetch();
    }

    /**
     * 级别变更记录
     * */
    public function levelChangeList()
    {
        $input = Request()->param();

        $username = $input['username'];
        $mobile = $input['mobile'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($username)) $where["u.username"] = ["like", "%" . $username . "%"];
        if (!empty($mobile)) $where["u.mobile"] = ["like", "%" . $mobile . "%"];

        if (!empty($start_time) && empty($end_time)) {
            $where["l.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["l.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["l.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('level_change l')->join('shop_user u', 'l.user_id = u.id', 'left')
            ->field('l.user_id,l.do_user_id,u.username,u.mobile,l.level,l.old_level,l.reason,l.create_time')
            ->where($where)
            ->order('l.create_time desc')
            ->paginate()->each(function ($val) {
                $username = Db::name('user')->where(['id' => $val['user_id']])->value('username');
                $val['username'] = $username;
                $do_username = Db::name('user')->where(['id' => $val['do_user_id']])->value('username');
                $val['do_username'] = $do_username;

                return $val;
            });
        $this->assign('list', $list);

        $this->assign('title', '级别变更记录');
        return $this->view->fetch();
    }

    /**
     * 赠品列表
     */
    public function goodsGiftList()
    {
        $input = Request()->param();

        $gift_name = $input['gift_name'];

        $where["is_del"] = 0;
        if (!empty($gift_name)) $where["gift_name"] = ["like", "%" . $gift_name . "%"];

        $list = Db::name('goods_gift')->where($where)->order('create_time desc')->paginate()->each(
            function ($v) {
                return $v;
            }
        );
        $this->assign('list', $list);

        $this->assign('title', '赠品列表');

        return $this->fetch();
    }

    /**
     * 修改新增赠品
     */
    public function doGoodsGift()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input["id"];
            $gift_name = $input["gift_name"];
            $gift_img = $input["gift_img"];
            $gift_price = $input["gift_price"];
            $start_date = $input["start_date"];
            $end_date = $input["end_date"];

            if (empty($gift_name)) adminReturn(2, "请输入赠品名称");
            if (empty($gift_img)) adminReturn(2, "请上传封面图片");
            if (empty($gift_price)) adminReturn(2, "请输入赠品价格");
            if (empty($start_date)) adminReturn(2, "请选择赠品开始时间");
            if (empty($end_date)) adminReturn(2, "请选择赠品结束时间");

            if ($gift_price <= 0) adminReturn(2, "价格不能小于等于零");
            if (strtotime($start_date) > strtotime($end_date)) adminReturn(2, "开始时间不能大于结束时间");

            $data = [
                "gift_name" => $gift_name,
                "gift_img" => $gift_img,
                "gift_price" => $gift_price,
                "start_date" => $start_date,
                "end_date" => $end_date
            ];

            if ($id > 0) {
                $data['update_time'] = time();
                $res = Db::name('goods_gift')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑赠送商品成功', url('goodsGiftList'));
                } else {
                    adminReturn(2, '编辑赠送商品失败或未编辑');
                }
            } else {
                $data['create_time'] = time();
                $res = Db::name('goods_gift')->insert($data);
                if ($res) {
                    adminReturn(1, '新增赠送商品成功', url('goodsGiftList'));
                } else {
                    adminReturn(2, '新增赠送商品失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('goods_gift')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . "赠送商品");

            return $this->view->fetch();
        }
    }

    /**
     * 删除赠品
     */
    public function delGoodsGiftList()
    {
        $input = Request()->param();
        $id = $input["id"];

        $data = [
            "is_del" => 1
        ];

        if ($id > 0) {
            $res = Db::name('goods_gift')->where(['id' => $id])->update($data);
            if ($res) {
                adminReturn(1, '删除赠送商品成功', url('goodsGiftList'));
            } else {
                adminReturn(2, '删除送商品失败');
            }
        }
    }

    /**
     * 新增商品评价
     * */
    public function doGoodsComment()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $goods_id = $input['goods_id'];
            $user_id = $input['user_id'];
            $imgs = $input['imgs'];
            $content = $input['content'];
            $star = $input['star'];

            if (empty($goods_id)) adminReturn(2, '商品ID缺失');
            if (empty($user_id)) adminReturn(2, '请选择评价用户');
            if (empty($content)) adminReturn(2, '请输入评价内容');

            $data = [
                'goods_id' => $goods_id,
                'user_id' => $user_id,
                'imgs' => $imgs,
                'content' => $content,
                'star' => $star,
                'create_time' => time()
            ];

            $res = Db::name('goods_comment')->insert($data);
            if ($res) {
                adminReturn(1, '新增商品评价成功', url('commentList', ['goods_id' => $goods_id]));
            } else {
                adminReturn(2, '新增商品评价失败');
            }
        } else {
            $user_list = Db::name('user')->select();
            $this->assign('user_list', $user_list);

            $this->assign('title', "新增商品评价");

            return $this->view->fetch();
        }
    }

    /**
     * 商品评价列表
     * */
    public function commentList()
    {
        $input = Request()->param();

        $goods_id = $input['goods_id'];

        if (empty($goods_id)) apiReturn(2, '商品ID缺失');

        $list = Db::name('goods_comment gc')
            ->join('shop_user u', 'gc.user_id = u.id', 'left')
            ->field('gc.id,u.username,u.mobile,gc.content,gc.star,gc.imgs,gc.create_time')
            ->where(['gc.goods_id' => $goods_id])
            ->order('gc.create_time desc')
            ->paginate()->each(function ($v) {
                $v['imgs_arr'] = doImgs($v['imgs']);

                return $v;
            });
        $this->assign('list', $list);

        $this->assign('title', '商品评价列表');

        return $this->view->fetch();
    }

    /**
     * 删除商品评价
     * */
    public function delComment()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '商品评价ID缺失');

        $info = Db::name('goods_comment')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('goods_comment')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }


    /**
     * 订单列表
     */
    public function orderList()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $order_number = $input['order_number'];
        $status = $input['status'];
        $after_status = $input['after_status'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($mobile)) $where["b.mobile"] = ["like", "%" . $mobile . "%"];
        if (!empty($order_number)) $where["a.order_number"] = ["like", "%" . $order_number . "%"];
        if (!empty($status)) $where["a.status"] = $status;
        if (!empty($after_status)) $where["a.after_status"] = $after_status;

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }
        $where["a.id"] = ["gt", 0];
        $list = Db::name('order a')->field("a.*,b.mobile,b.username")->join('user b', "a.user_id = b.id", "left")->where($where)->order('create_time desc')->paginate()->each(
            function ($v) {
                if ($v['status'] == 1) {
                    $v['status_text'] = "待付款";
                } elseif ($v['status'] == 2) {
                    $v['status_text'] = "待发货";
                } elseif ($v['status'] == 3) {
                    $v['status_text'] = "待收货";
                } elseif ($v['status'] == 4) {
                    $v['status_text'] = "待评价";
                } elseif ($v['status'] == 5) {
                    $v['status_text'] = "已完成";
                } elseif ($v['status'] == 7) {
                    $v['status_text'] = "售后中";
                } elseif ($v['status'] == 8) {
                    $v['status_text'] = "售后完成";
                } elseif ($v['status'] == 10) {
                    $v['status_text'] = "已取消";
                } else {
                    $v['status_text'] = "未知";
                }

                if ($v['after_status'] == 0) {
                    $v['after_status_text'] = "未售后";
                } elseif ($v['after_status'] == 1) {
                    $v['after_status_text'] = "售后中";
                } elseif ($v['after_status'] == 2) {
                    $v['after_status_text'] = "售后成功";
                } elseif ($v['after_status'] == 3) {
                    $v['after_status_text'] = "售后失败";
                } else {
                    $v['after_status_text'] = "未知";
                }

                if ($v['pay_type'] == 1) {
                    $v['pay_type_text'] = "微信支付";
                } elseif ($v['pay_type'] == 2) {
                    $v['pay_type_text'] = "收益支付";
                } else {
                    $v['pay_type_text'] = "未知";
                }
                return $v;
            }


        );
        $this->assign('list', $list);

        $all_pay_price = Db::name('order a')->join('user b', "a.user_id = b.id", "left")->where($where)->sum('pay_price');
        $this->assign('all_pay_price', sprintf('%.2f', $all_pay_price));

        $this->assign('title', '订单列表');

        return $this->fetch();
    }

    /**
     * 订单导出
     */
    public function order_data_to_exe()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $order_number = $input['order_number'];
        $status = $input['status'];
        $after_status = $input['after_status'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($mobile)) $where["b.mobile"] = ["like", "%" . $mobile . "%"];
        if (!empty($order_number)) $where["a.order_number"] = ["like", "%" . $order_number . "%"];
        if (!empty($status)) $where["a.status"] = $status;
        if (!empty($after_status)) $where["a.after_status"] = $after_status;

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }
        $where["a.id"] = ["gt", 0];
        $list = Db::name('order a')->field("a.*,b.mobile,b.username")->join('user b', "a.user_id = b.id", "left")
            ->where($where)->order('create_time desc')->select();

    }

    /**
     * 订单详情
     */
    public function doOrder()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input["id"];

            $order_info = Db::name("order")->where(["id" => $id])->find();
            if ($order_info['status'] == 2) {
                $status = 3;
                $express_id = $input["express_id"];
                $send_num = $input["send_num"];
                if (empty($send_num)) adminReturn(2, "请输入快递编号");
                Db::startTrans();
                $data = [
                    "status" => $status,
                    "express_id" => $express_id,
                    "send_num" => $send_num,
                ];

                $data['update_time'] = time();
                $res = Db::name('order')->where(['id' => $id])->update($data);
                if ($res) {
                    /** 添加发送消息 */
                    $data_msg = [
                        "user_id" => $order_info["user_id"],
                        "order_id" => $id,
                        "title" => "您的订单已经发货",
                        "content" => "您的订单已经发货",
                        "type" => 1,
                        "create_time" => time(),
                    ];
                    Db::name("msg")->insert($data_msg);

                    /** 添加15天自动确认收货计划 */
                    $time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                    $data_plan = [
                        "user_id" => $order_info["user_id"],
                        "order_id" => $id,
                        "type" => 2,
                        "execute_date" => date('Y-m-d', $time),
                    ];
                    Db::name("plan")->insert($data_plan);

                    Db::commit();
                    adminReturn(1, '编辑成功', url('orderList'));
                } else {
                    Db::rollback();
                    adminReturn(2, '系统繁忙，请稍后再试');
                }
            } elseif ($order_info['status'] == 7) {
                $after_status = $input['after_status'];
                $after_refuse_reason = $input['after_refuse_reason'];
                if (empty($after_status)) adminReturn(2, '请选择售后操作');
                if ($after_status == 3 && empty($after_refuse_reason)) adminReturn(2, "请输入拒绝原因");

                $time = time();

                Db::startTrans();
                try {
                    $data = [
                        'back_order_sn' => $order_info['pay_order_sn'],
                        'status' => 8,//订单状态改成售后完成
                        'after_status' => $after_status,
                        'after_refuse_reason' => $after_refuse_reason,
                        'update_time' => $time
                    ];
                    Db::name('order')->where(['id' => $id])->update($data);

                    $price = $order_info['pay_price'];
                    /**
                     * 同意售后【退货退款】（对应支付成功做退回处理）
                     * 1：金额原路退回（微信退款 || 收益退款）  注：如果是收益退款的话需要生成对应的收益记录，且用户可用收益增加
                     * 3：减少商品销量
                     * 4：增加商品库存
                     * 5：如果用户是首单申请售后，用户is_activation修改为未激活状态
                     * 6：冻结的直推、级差、服务津贴作废（作废）
                     * 7：删除自动确认收货任务（作废）
                     * 同意售后【换货】
                     * 1：订单变成待收货状态
                     * 2：删除原来的自动确认收货任务
                     * 3：新增自动确认收货任务
                     * 拒绝售后
                     * 1：将订单改回申请售后前的状态
                     * 2：如果订单申请售后前是【待收货】状态，基于拒绝售后那一刻起加上自动确认收货任务
                     * */
                    if ($after_status == 2) {
                        // 同意售后

                        if ($input['after_type'] == '退货退款') {
                            $vice_order_info = Db::name('vice_order')->where(['order_id' => $id])->find();

                            // 1：金额原路退回
                            //                            if ($order_info['pay_type'] == 1) {
                            //微信支付
                            /*Loader::import('wxpaysdk\wxPay', EXTEND_PATH);
                            $obj = new \wxPay();

                            $obj->refund($price, $price, $order_info['pay_order_sn'], $order_info['pay_order_sn'], $order_info['after_reason']);*/
                            //                            } else {
                            $user_id = $order_info['user_id'];

                            $user_info = Db::name('user')->where(['id' => $user_id])->find();
                            $mobile = $user_info['mobile'] ? : '';
                            //                                $gzh_openid = $user_info['gzh_openid'];

                            Db::name('user')->where(['id' => $user_id])->setInc('all_profit', $price);

                            //收益支付
                            $profit_data = [
                                'order_id' => $id,
                                'user_id' => $order_info['user_id'],
                                'price' => $order_info['pay_price'],
                                'type' => 12,
                                'status' => 2,
                                'create_time' => $time
                            ];
                            Db::name('profit')->insert($profit_data);

                            // 发送微信公众号模板消息
                            /*$template_msg = [
                                'first' => [
                                    'value' => '您好，您的售后订单购物抵扣收益已退回',
                                    'color' => '#743A3A'
                                ],
                                'keyword1' => [
                                    'value' => '购物抵扣收益退款',
                                    'color' => '#743A3A'
                                ],
                                'keyword2' => [
                                    'value' => $price,
                                    'color' => '#743A3A'
                                ],
                                'keyword3' => [
                                    'value' => date('Y-m-d'),
                                    'color' => '#743A3A'
                                ],
                                'keyword4' => [
                                    'value' => '点击查看',
                                    'color' => '#743A3A'
                                ],
                                'remark' => [
                                    'value' => '',
                                    'color' => '#743A3A'
                                ]
                            ];
                            $page = 'pages/my_income/my_income';
                            if ($gzh_openid && $price > 0) sendWxTemplateNotice($gzh_openid, $template_msg, 12, $page);*/
                            //                            }

                            $buy_count = $vice_order_info['count'];
                            $goods_id = $vice_order_info['goods_id'];
                            $sku_id = $vice_order_info['sku_id'];

                            // 3：减少商品销量
                            $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                            if ($goods_info && $buy_count > 0) Db::name('goods')->where(['id' => $goods_id])->setDec('sales_count', $buy_count);

                            // 4：增加商品库存
                            $sku_info = Db::name('sku_value')->where(['goods_id' => $goods_id, 'sku_id' => $sku_id])->find();
                            if ($sku_info && $buy_count > 0) Db::name('sku_value')->where(['goods_id' => $goods_id, 'sku_id' => $sku_id])->setInc('stock', $buy_count);

                            // 5：如果用户是首单申请售后，用户is_activation修改为未激活状态
                            //                            if ($order_info['is_first_order'] == 1) Db::name('user')->where(['id' => $user_id])->setField('is_activation', 0);

                            // 6：冻结的直推、级差、服务津贴作废（作废）
                            /*$frozen_profit_list = Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->select();
                            if ($frozen_profit_list) {
                                $update_profit_data = [
                                    'status' => -1,
                                    'update_time' => $time
                                ];
                                Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->update($update_profit_data);
                            }*/

                            // 7：删除自动确认收货任务
                            //                            Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();
                        } else if ($input['after_type'] == '换货') {
                            // 1：订单变成待收货状态
                            $change_order_data = [
                                'status' => 3,
                                'update_time' => $time
                            ];
                            Db::name('order')->where(['id' => $id])->update($change_order_data);
                            // 2：删除原来的自动确认收货任务
                            Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();
                            // 3：新增自动确认收货任务
                            $time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                            $data_plan = [
                                "user_id" => $order_info["user_id"],
                                "order_id" => $id,
                                "type" => 2,
                                "execute_date" => date('Y-m-d', $time),
                            ];
                            Db::name("plan")->insert($data_plan);
                        }
                    } elseif ($after_status == 3) {
                        // 拒绝售后

                        // 1：将订单改回申请售后前的状态
                        if ($order_info['send_num']) {
                            // 存在订单号，说明订单售后前已发货
                            $edit_status = 3;// 待收货

                            // 2：如果订单申请售后前是【待收货】状态，基于拒绝售后那一刻起加上自动确认收货任务

                            /** 添加15天自动确认收货计划 */
                            $time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                            $data_plan = [
                                "user_id" => $order_info["user_id"],
                                "order_id" => $id,
                                "type" => 2,
                                "execute_date" => date('Y-m-d', $time),
                            ];
                            Db::name("plan")->insert($data_plan);
                        } else {
                            $edit_status = 2;// 待发货
                        }

                        Db::name('order')->where(['id' => $id])->setField('status', $edit_status);
                    }

                    Db::commit();
                    adminReturn(1, '操作成功', url('orderList'));
                } catch (\Exception $e) {
                    Db::rollback();
                    adminReturn(2, '系统繁忙，请稍后再试~');
                }
            }
        } else {
            $id = input("id");
            $order_info = Db::name('order a')->field("a.*,b.mobile,b.username")->where(["a.id" => $id])->join('user b', "a.user_id = b.id", "left")->find();
            $order_vice = Db::name("vice_order")->where(["order_id" => $id])->select();
            foreach ($order_vice as &$vo) {
                $suk_value_arr = explode("-", $vo['sku_id']);
                $suk_name_str = "";
                foreach ($suk_value_arr as $vv) {
                    $sku_info = Db::name("sku")->where(["id" => $vv])->find();
                    $sku_p_info = Db::name("sku")->where(["id" => $sku_info['pid']])->find();
                    $suk_name_str .= $sku_p_info['name'] . ": " . $sku_info['name'] . ";";
                }
                $vo['suk_name_str'] = $suk_name_str;
                $gift_ids_arr = explode("-", $vo['gift_ids']);
                $gift_arr = [];
                foreach ($gift_ids_arr as $vg) {
                    $gift_arr[] = Db::name("goods_gift")->where(["id" => $vg])->find();
                }
                $vo['gift_arr'] = $gift_arr;

                /** 查看商品是不是有评论 */
                $is_have = Db::name('goods_comment')->where(["order_id" => $id, "goods_id" => $vv['goods_id']])->value("id");
                if ($is_have) {
                    $is_comment = $is_have;
                } else {
                    $is_comment = 0;
                }
                $vo['is_comment'] = $is_comment;
            }

            //查询出快递公司
            $express_list = Db::name("express")->field("id,name")->select();

            if ($express_id = $order_info['express_id']) $order_info['express_name'] = Db::name('express')->where(['id' => $express_id])->value('name');

            $this->assign('info', $order_info);
            $this->assign('order_vice', $order_vice);
            $this->assign('express_list', $express_list);

            $this->assign('title', '订单详情');
            return $this->fetch();
        }
    }

    /**
     *商品评论
     */
    public function doComment()
    {
        $input = Request()->param();
        $id = $input["id"];

        //查询出评论内容
        $info = Db::name('goods_comment')->where(["id" => $id])->find();

        $info["img_arr"] = explode(",", $info["imgs"]);

        $this->assign('info', $info);
        $this->assign('title', '评论详情');
        return $this->fetch();
    }

    /**
     *提现申请
     */
    public function withdrawalList()
    {
        $input = Request()->param();

        $username = $input['username'];
        $status = $input['status'];

        $where["a.id"] = ['gt', 0];
        if (!empty($username)) $where["b.username"] = ["like", "%" . $username . "%"];
        if (!empty($status)) $where["a.status"] = $status;

        $list = Db::name('withdrawal a')->field("a.*,b.username,b.level")->where($where)->join('user b', "a.user_id = b.id", "left")
            ->order('status asc,create_time desc')->paginate()->each(
                function ($v) {
                    if ($v['type'] == 1) {
                        $v['type_txt'] = "微信提现";
                    } else {
                        $v['type_txt'] = "银行卡提现";
                    }

                    if ($v['status'] == 0) {
                        $v['status_txt'] = "提现申请中";
                    } elseif ($v['status'] == 1) {
                        $v['status_txt'] = "提现成功";
                    } else {
                        $v['status_txt'] = "提现失败";
                    }
                    return $v;
                }
            );
        $this->assign('list', $list);

        $this->assign('title', '提现申请');

        return $this->fetch();
    }

    /**
     * 提现审核
     */
    public function doWithdrawal()
    {
        $input = Request()->param();

        $id = $input['id'];
        $status = $input['status'];
        if (empty($id)) adminReturn(2, '提现记录ID缺失');

        $time = time();

        $info = Db::name('withdrawal')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '提现记录不存在或已删除');

        $user_id = $info['user_id'];
        $user_price = $info['price'];     //提现收益
        $real_price = $info['real_price'];//实际到账金额

        $gzh_openid = Db::name('user')->where(['id' => $user_id])->value('gzh_openid');

        $data = [
            "status" => $status,
            "update_time" => $time,
        ];

        Db::startTrans();
        try {
            Db::name('withdrawal')->where(["id" => $id])->update($data);

            $msg_data = [
                'user_id' => $user_id,
                'type' => 2,
                'create_time' => $time
            ];

            if ($status == 1) {
                // 提现审核通过
                $data_add = [
                    'user_id' => $user_id,
                    'price' => $user_price,
                    'type' => 5,
                    'status' => 2,
                    'create_time' => $time
                ];
                Db::name('profit')->insert($data_add);

                // 发送微信公众号模板消息
                $template_msg = [
                    'first' => [
                        'value' => '您好，您成功提现' . $user_price . '收益，实际到账金额：' . $real_price . '元',
                        'color' => '#743A3A'
                    ],
                    'keyword1' => [
                        'value' => $real_price . '元',
                        'color' => '#743A3A'
                    ],
                    'keyword2' => [
                        'value' => date('Y-m-d'),
                        'color' => '#743A3A'
                    ],
                    'keyword3' => [
                        'value' => '您的提现申请已通过审核',
                        'color' => '#743A3A'
                    ],
                    'remark' => [
                        'value' => '',
                        'color' => '#743A3A'
                    ]
                ];
                if ($gzh_openid && $real_price > 0) sendWxTemplateNotice($gzh_openid, $template_msg, 5);

                // 发送站内系统通知
                $msg_data['title'] = '提现成功';
                $msg_data['content'] = '您好，您成功提现' . $user_price . '收益，实际到账金额：' . $real_price . '元';
                Db::name('msg')->insert($msg_data);

                Db::commit();
                adminReturn(1, '审核成功', url('withdrawalList'));
            } else {
                // 提现审核驳回

                // 用户可用收益返还
                Db::name('user')->where(['id' => $user_id])->setInc('all_profit', $user_price);

                // 新增系统通知
                $msg_data['title'] = '提现失败';
                $msg_data['content'] = '提现失败';
                Db::name('msg')->insert($msg_data);

                // 收益提现失败返还收益
                $profit_data = [
                    'user_id' => $user_id,
                    'price' => $user_price,
                    'type' => 8,
                    'status' => 2,
                    'create_time' => $time
                ];
                Db::name('profit')->insert($profit_data);

                // 发送微信公众号模板消息
                $template_msg = [
                    'first' => [
                        'value' => '您好，您的收益提现审核未通过审核，返还' . $user_price . '收益',
                        'color' => '#743A3A'
                    ],
                    'keyword1' => [
                        'value' => $real_price,
                        'color' => '#743A3A'
                    ],
                    'keyword2' => [
                        'value' => date('Y-m-d'),
                        'color' => '#743A3A'
                    ],
                    'keyword3' => [
                        'value' => '您的提现申请未通过审核',
                        'color' => '#743A3A'
                    ],
                    'keyword4' => [
                        'value' => '',
                        'color' => '#743A3A'
                    ],
                    'remark' => [
                        'value' => '',
                        'color' => '#743A3A'
                    ]
                ];
                if ($gzh_openid && $real_price > 0) sendWxTemplateNotice($gzh_openid, $template_msg, 8);

                Db::commit();
                adminReturn(1, '操作成功', url('withdrawalList'));
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**
     * 销售奖励列表
     * */
    public function salesBonusList()
    {
        $list = Db::name('sales_bonus')->order('id desc')->paginate();

        $this->assign('list', $list);

        $this->assign('title', '销售奖励列表');
        return $this->view->fetch();
    }

    /**
     * 导出销售奖励
     * */
    public function exportSalesBonusList()
    {
        $title = '销售奖励';
        $th = ['结算周期', '周期平台总业绩', '结算比例', '总结算金额', '每人平均结算金额'];
        $td = ['date', 'all_price', 'rate', 'all_bonus', 'bonus_price'];
        $data = getSalesBonusList();

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 销售奖励详情
     * */
    public function salesBonusDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, '销售月结ID缺失');

        // 详细信息
        $info = Db::name('sales_bonus')->where(['id' => $id])->find();
        $this->assign('info', $info);

        // 待结算用户列表
        if ($user_ids = $info['user_ids']) {
            $wait_bonus_user_list = Db::name('user')->where(['id' => ['IN', $user_ids]])->order('is_change_level asc')->select();
            if ($wait_bonus_user_list) {
                foreach ($wait_bonus_user_list as $k => $v) {
                    $count = Db::name('profit')->where(['user_id' => $v['id'], 'year' => $info['year'], 'month' => $info['month'], 'type' => 6, 'status' => ['neq', -1]])->count();
                    if ($count > 0) unset($wait_bonus_user_list[$k]);
                }
                $wait_bonus_user_list = array_merge($wait_bonus_user_list);
            } else {
                $wait_bonus_user_list = [];
            }
        } else {
            $wait_bonus_user_list = [];
        }
        $this->assign('wait_bonus_user_list', $wait_bonus_user_list);

        // 已结算用户列表
        $bonus_user_list = Db::name('profit p')
            ->field('p.id,u.username,u.mobile,p.price,p.remark,u.is_change_level')
            ->join('shop_user u', 'p.user_id = u.id', 'left')
            ->where(['p.year' => $info['year'], 'p.month' => $info['month'], 'p.type' => 6, 'p.status' => ['neq', -1]])
            ->order('u.is_change_level asc')
            ->select();
        $this->assign('bonus_user_list', $bonus_user_list);

        $this->assign('title', '销售奖励详情');
        return $this->view->fetch();
    }

    /**
     * 销售奖励月结
     * */
    public function salesBonusSend()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];
        $price = $input['price'];
        $remark = $input['remark'];

        if (empty($id)) adminReturn(2, '销售奖励ID缺失');
        if (empty($user_id)) adminReturn(2, '用户ID缺失');
        if (empty($price) || $price <= 0) adminReturn(2, '请输入正确的结算金额');

        Db::startTrans();
        try {
            $info = Db::name('sales_bonus')->where(['id' => $id])->find();
            if ($info) {
                if (!in_array($user_id, explode(',', $info['user_ids']))) adminReturn(2, '销售奖励用户名单中未查询到该用户');

                $time = time();
                if ($price > 0) {
                    $remark = $remark ? : ($info['year'] . '-' . $info['month'] . '销售奖励月结');

                    // 新增收益记录
                    $data = [
                        'user_id' => $user_id,
                        'price' => $price,
                        'type' => 6,
                        'year' => $info['year'],
                        'month' => $info['month'],
                        'remark' => $remark,
                        'status' => 2,
                        'create_time' => time()
                    ];
                    Db::name('profit')->insert($data);

                    // 增加用户可用收益
                    Db::name('user')->where(['id' => $user_id])->setInc('all_profit', $price);

                    // 新增系统消息
                    $msg_data = [
                        'user_id' => $user_id,
                        'title' => '销售奖励月结',
                        'content' => $remark,
                        'type' => 2,
                        'create_time' => $time
                    ];
                    Db::name('msg')->insert($msg_data);

                    // 发送微信公众号模板消息
                    $template_msg = [
                        'first' => [
                            'value' => '您好，您已获得上月' . $price . '收益',
                            'color' => '#743A3A'
                        ],
                        'keyword1' => [
                            'value' => '销售奖励',
                            'color' => '#743A3A'
                        ],
                        'keyword2' => [
                            'value' => $price,
                            'color' => '#743A3A'
                        ],
                        'keyword3' => [
                            'value' => date('Y-m-d'),
                            'color' => '#743A3A'
                        ],
                        'keyword4' => [
                            'value' => '点击查看',
                            'color' => '#743A3A'
                        ],
                        'remark' => [
                            'value' => $remark,
                            'color' => '#743A3A'
                        ]
                    ];
                    $user_info = Db::name('user')->field('mobile,gzh_openid')->where(['id' => $user_id])->find();

                    $gzh_openid = $user_info['gzh_openid'];
                    $mobile = $user_info['mobile'];
                    $page = 'pages/my_income/my_income';

                    if ($gzh_openid) sendWxTemplateNotice($gzh_openid, $template_msg, 6, $page);
                }

                Db::commit();
                adminReturn(1, '结算成功');
            } else {
                Db::rollback();
                adminReturn(2, '销售奖励不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**
     * 退休基金列表
     * */
    public function retireFundList()
    {
        $list = Db::name('retire_fund')->order('id desc')->paginate();

        $this->assign('list', $list);

        $this->assign('title', '退休基金列表');
        return $this->view->fetch();
    }

    /**
     * 导出退休基金
     * */
    public function exportRetireFundList()
    {
        $title = '退休基金';
        $th = ['档数', '结算周期', '周期平台总业绩', '结算比例', '结算金额', '叠算总金额', '每人平均叠算金额'];
        $td = ['gear', 'date', 'all_price', 'rate', 'rate_all_price', 'all_retire_price', 'retire_price'];
        $data = getRetireFundList();

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 退休基金详情
     * */
    public function retireFundDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, '退休基金ID缺失');

        // 详细信息
        $info = Db::name('retire_fund')->where(['id' => $id])->find();
        $this->assign('info', $info);

        // 待结算用户列表
        if ($user_ids = $info['user_ids']) {
            $wait_retire_user_list = Db::name('user')->where(['id' => ['IN', $user_ids]])->order('is_change_level asc')->select();
            if ($wait_retire_user_list) {
                foreach ($wait_retire_user_list as $k => $v) {
                    $count = Db::name('profit')->where(['user_id' => $v['id'], 'year' => $info['year'], 'month' => $info['month'], 'type' => 7, 'status' => ['neq', -1]])->count();
                    if ($count > 0) unset($wait_retire_user_list[$k]);
                }
                $wait_retire_user_list = array_merge($wait_retire_user_list);
            } else {
                $wait_retire_user_list = [];
            }
        } else {
            $wait_retire_user_list = [];
        }
        $this->assign('wait_retire_user_list', $wait_retire_user_list);

        // 已结算用户列表
        $retire_user_list = Db::name('profit p')
            ->field('p.id,u.username,u.mobile,p.price,p.remark,u.is_change_level')
            ->join('shop_user u', 'p.user_id = u.id', 'left')
            ->where(['p.year' => $info['year'], 'p.month' => $info['month'], 'p.type' => 7, 'p.status' => ['neq', -1]])
            ->order('u.is_change_level asc')
            ->select();
        $this->assign('retire_user_list', $retire_user_list);

        $this->assign('title', '退休基金详情');
        return $this->view->fetch();
    }

    /**
     * 退休基金结算
     * */
    public function retireFundSend()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];
        $price = $input['price'];
        $remark = $input['remark'];

        if (empty($id)) adminReturn(2, '退休基金ID缺失');
        if (empty($user_id)) adminReturn(2, '用户ID缺失');
        if (empty($price) || $price <= 0) adminReturn(2, '请输入正确的结算金额');

        Db::startTrans();
        try {
            $info = Db::name('retire_fund')->where(['id' => $id])->find();
            if ($info) {
                if (!in_array($user_id, explode(',', $info['user_ids']))) adminReturn(2, '退休基金用户名单中未查询到该用户');

                $time = time();
                if ($price > 0) {
                    $remark = $remark ? : ($info['year'] . '-' . $info['month'] . '退休基金月结');

                    // 新增收益记录
                    $data = [
                        'user_id' => $user_id,
                        'price' => $price,
                        'type' => 7,
                        'year' => $info['year'],
                        'month' => $info['month'],
                        'remark' => $remark,
                        'status' => 2,
                        'create_time' => $time
                    ];
                    Db::name('profit')->insert($data);

                    // 新增系统消息
                    $msg_data = [
                        'user_id' => $user_id,
                        'title' => '退休基金月结',
                        'content' => $remark,
                        'type' => 2,
                        'create_time' => $time
                    ];
                    Db::name('msg')->insert($msg_data);

                    // 增加用户可用收益
                    Db::name('user')->where(['id' => $user_id])->setInc('all_profit', $price);

                    // 发送微信公众号模板消息
                    $template_msg = [
                        'first' => [
                            'value' => '您好，您已获得上月' . $price . '收益：',
                            'color' => '#743A3A'
                        ],
                        'keyword1' => [
                            'value' => '退休基金',
                            'color' => '#743A3A'
                        ],
                        'keyword2' => [
                            'value' => $price,
                            'color' => '#743A3A'
                        ],
                        'keyword3' => [
                            'value' => date('Y-m-d'),
                            'color' => '#743A3A'
                        ],
                        'keyword4' => [
                            'value' => '点击查看',
                            'color' => '#743A3A'
                        ],
                        'remark' => [
                            'value' => $remark,
                            'color' => '#743A3A'
                        ]
                    ];
                    $user_info = Db::name('user')->field('mobile,gzh_openid')->where(['id' => $user_id])->find();

                    $gzh_openid = $user_info['gzh_openid'];
                    $mobile = $user_info['mobile'];
                    $page = 'pages/my_income/my_income';

                    if ($gzh_openid) sendWxTemplateNotice($gzh_openid, $template_msg, 7, $page);
                }

                Db::commit();
                adminReturn(1, '结算成功');
            } else {
                Db::rollback();
                adminReturn(2, '退休基金不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**
     * 门店补贴列表
     * */
    public function shopSubsidyList()
    {
        $input = Request()->param();

        $status = $input['status'];

        if ($status) $where['status'] = $status;

        $list = Db::name('shop_subsidy')->where($where)->order('status asc,create_time desc')->paginate()->each(function ($val) {
            $val['shop_name'] = Db::name('shop')->where(['id' => $val['shop_id']])->value('name');
            $val['username'] = Db::name('user')->where(['id' => $val['user_id']])->value('username');

            return $val;
        });

        $this->assign('list', $list);

        $this->assign('title', '门店补贴列表');
        return $this->view->fetch();
    }

    /**
     * 导出门店补贴
     * */
    public function exportShopSubsidyList()
    {
        $input = Request()->param();

        $status = $input['status'];

        $title = '门店补贴';
        $th = ['结算周期', '周期平台总业绩', '门店', '用户', '补贴比例', '门店补贴金额', '结算状态', '实际结算金额', '结算备注'];
        $td = ['date', 'all_price', 'shop_name', 'username', 'rate', 'price', 'status', 'send_price', 'remark'];
        $data = getShopSubsidyList($status);

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 门店补贴结算
     * */
    public function shopSubsidySend()
    {
        $input = Request()->param();

        $id = $input['id'];
        $price = $input['price'];
        $remark = $input['remark'];

        if (empty($id)) adminReturn(2, '门店补贴ID缺失');

        $info = Db::name('shop_subsidy')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $time = time();

                if ($price > 0) {

                    $remark = $remark ? : ($info['year'] . '-' . $info['month'] . '门店补贴月结');

                    // 门店补贴数据修改
                    $send_data = [
                        'send_price' => $price,
                        'remark' => $remark,
                        'status' => 2,
                        'update_time' => $time
                    ];
                    Db::name('shop_subsidy')->where(['id' => $id])->update($send_data);

                    // 新增收益记录
                    $profit_data = [
                        'user_id' => $info['user_id'],
                        'price' => $price,
                        'type' => 9,
                        'year' => $info['year'],
                        'month' => $info['month'],
                        'remark' => $remark,
                        'status' => 2,
                        'create_time' => $time
                    ];
                    Db::name('profit')->insert($profit_data);

                    // 新增系统消息
                    $msg_data = [
                        'user_id' => $info['user_id'],
                        'title' => '门店补贴月结',
                        'content' => $remark,
                        'type' => 2,
                        'create_time' => $time
                    ];
                    Db::name('msg')->insert($msg_data);

                    // 增加用户可用收益
                    Db::name('user')->where(['id' => $info['user_id']])->setInc('all_profit', $price);

                    // 发送微信公众号模板消息
                    $template_msg = [
                        'first' => [
                            'value' => '您好，您已获得上月' . $price . '收益：',
                            'color' => '#743A3A'
                        ],
                        'keyword1' => [
                            'value' => '门店区域补贴',
                            'color' => '#743A3A'
                        ],
                        'keyword2' => [
                            'value' => $price,
                            'color' => '#743A3A'
                        ],
                        'keyword3' => [
                            'value' => date('Y-m-d'),
                            'color' => '#743A3A'
                        ],
                        'keyword4' => [
                            'value' => '点击查看',
                            'color' => '#743A3A'
                        ],
                        'remark' => [
                            'value' => $remark,
                            'color' => '#743A3A'
                        ]
                    ];

                    $user_info = Db::name('user')->field('mobile,gzh_openid')->where(['id' => $info['user_id']])->find();

                    $gzh_openid = $user_info['gzh_openid'];
                    $mobile = $user_info['mobile'];
                    $page = 'pages/my_income/my_income';

                    if ($gzh_openid) sendWxTemplateNotice($gzh_openid, $template_msg, 9, $page);
                }

                Db::commit();
                adminReturn(1, '结算成功');
            } catch (\Exception $e) {
                adminReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            adminReturn(2, '门店补贴不存在或已删除');
        }

    }

    /**
     * 财务统计
     * */
    public function censusProfit()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($start_time) && empty($end_time)) {
            $all_consume_where["complete_time"] = ["egt", strtotime($start_time)];
            $all_consume_no_get_where["create_time"] = ["egt", strtotime($start_time)];
            $all_withdraw_where["create_time"] = ["egt", strtotime($start_time)];
            $all_recharge_where['create_time'] = ["egt", strtotime($start_time)];
            $all_send_profit_where['create_time'] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $all_consume_where["complete_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
            $all_consume_no_get_where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
            $all_withdraw_where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
            $all_recharge_where['create_time'] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
            $all_send_profit_where['create_time'] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $all_consume_where["complete_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
            $all_consume_no_get_where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
            $all_withdraw_where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
            $all_recharge_where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
            $all_send_profit_where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        // 总累计销售额
        $all_consume_where['is_pay'] = 1;        //已付款
        $all_consume_where['back_order_sn'] = '';//未退款的
        $all_consume = Db::name('order')->where($all_consume_where)->sum('pay_price');

        // 总销售额
        $all_consume_no_get_where['complete_time'] = ['gt', 0];
        $all_consume_no_get = Db::name('order')->where($all_consume_no_get_where)->sum('pay_price');

        // 应发收益总统计
        $all_send_profit = Db::name('profit')->where($all_send_profit_where)->where(['type' => ['IN', [1, 2, 3, 6, 7, 9]]])->sum('price');

        // 成功提现总额度统计
        $all_withdraw = Db::name('profit')->where($all_withdraw_where)->where(['type' => 5])->sum('price');

        // 充值总金额
        $all_recharge = Db::name('profit_change')->where($all_recharge_where)->sum('price');

        $info = [
            'all_consume' => sprintf("%.2f", $all_consume),
            'all_consume_no_get' => sprintf("%.2f", $all_consume_no_get),
            'all_send_profit' => sprintf("%.2f", $all_send_profit),
            'all_withdraw' => sprintf("%.2f", $all_withdraw),
            'all_recharge' => sprintf("%.2f", $all_recharge),
        ];
        $this->assign('info', $info);

        $this->assign('title', '财务统计');
        return $this->view->fetch();
    }

    /**
     * 导出财务统计
     * */
    public function exportCensusProfit()
    {
        $input = Request()->param();

        $start_time = $input['start_time'] ? : '';
        $end_time = $input['end_time'] ? : '';

        $title = '财务统计';
        $th = ['总累计销售额', '总销售额', '应发收益总统计', '成功提现总额度统计', '充值总金额'];
        $td = ['all_consume', 'all_consume_no_get', 'all_send_profit', 'all_withdraw', 'all_recharge'];
        $data = getCensusProfit($start_time, $end_time);

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 开支明细（一级）
     * */
    public function spendCensusList()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $select_list = Db::name('profit')->distinct(true)->field('FROM_UNIXTIME( create_time, "%Y-%m-%d") date')->where($where)->where(['type' => ['IN', [1, 2, 3, 6, 7, 9]], 'status' => ['neq', -1]])->select();
        $count = count($select_list);

        $list = Db::name('profit')->distinct(true)->field('FROM_UNIXTIME( create_time, "%Y-%m-%d") date')->where($where)->where(['type' => ['IN', [1, 2, 3, 6, 7, 9]], 'status' => ['neq', -1]])->order('create_time desc')->paginate(Config('paginate.list_rows'), $count)->each(function ($v) {
            // 消费收益
            $consume_profit = dayAllProfit($v['date'], 1);
            $v['consume_profit'] = $consume_profit;
            // 绩效收益
            $achievements_profit = dayAllProfit($v['date'], 2);
            $v['achievements_profit'] = $achievements_profit;
            // 服务津贴
            $service_profit = dayAllProfit($v['date'], 3);
            $v['service_profit'] = $service_profit;
            // 门店区域补贴
            $shop_profit = dayAllProfit($v['date'], 9);
            $v['shop_profit'] = $shop_profit;
            // 销售奖励
            $sales_profit = dayAllProfit($v['date'], 6);
            $v['sales_profit'] = $sales_profit;

            $start_time = strtotime($v['date']);
            $end_time = $start_time + 60 * 60 * 24 - 1;

            $where['create_time'] = ['between', [$start_time, $end_time]];

            // 一档退休基金
            $first_retire_profit = Db::name('retire_fund')->where($where)->where(['gear' => 'first_gear'])->value('all_retire_price');
            $v['first_retire_profit'] = sprintf('%.2f', $first_retire_profit);
            // 二档退休基金
            $second_retire_profit = Db::name('retire_fund')->where($where)->where(['gear' => 'second_gear'])->value('all_retire_price');
            $v['second_retire_profit'] = sprintf('%.2f', $second_retire_profit);
            // 三档退休基金
            $third_retire_profit = Db::name('retire_fund')->where($where)->where(['gear' => 'third_gear'])->value('all_retire_price');
            $v['third_retire_profit'] = sprintf('%.2f', $third_retire_profit);

            $all_price = $consume_profit + $achievements_profit + $service_profit + $shop_profit + $sales_profit + $first_retire_profit + $second_retire_profit + $third_retire_profit;
            $v['all_price'] = sprintf('%.2f', $all_price);

            return $v;
        });

        $this->assign('list', $list);

        $this->assign('title', '开支明细');
        return $this->view->fetch();
    }

    /**
     * 导出开支明细（一级）
     * */
    public function exportSpendCensusList()
    {
        $input = Request()->param();

        $start_time = $input['start_time'] ? : '';
        $end_time = $input['end_time'] ? : '';

        $title = '开支明细';
        $th = ['时间', '消费收益', '绩效收益', '服务津贴', '门店区域补贴', '销售奖励', '退休基金一档', '退休基金二档', '退休基金三档', '小计'];
        $td = ['date', 'consume_profit', 'achievements_profit', 'service_profit', 'shop_profit', 'sales_profit', 'first_retire_profit', 'second_retire_profit', 'third_retire_profit', 'all_price'];
        $data = getSpendCensusList($start_time, $end_time);

        exportExcel($title, $th, $td, $data);
    }


    /**
     * 开支明细（二级）
     * */
    public function spendCensusUserList()
    {
        $input = Request()->param();

        $date = $input['date'];
        $mobile = $input['mobile'];
        $username = $input['username'];

        if (empty($date)) adminReturn(2, '日期缺失');

        $start_time = strtotime($date);
        $end_time = $start_time + 60 * 60 * 24 - 1;

        if ($mobile) $search_where['u.mobile'] = ['like', '%' . $mobile . '%'];
        if ($username) $search_where['u.username'] = ['like', '%' . $username . '%'];

        $select_list = Db::name('profit p')->join('shop_user u', 'p.user_id = u.id', 'left')
            ->distinct(true)->field('p.user_id,FROM_UNIXTIME( p.create_time, "%Y-%m-%d") date')
            ->where($search_where)
            ->where(['p.type' => ['IN', [1, 2, 3, 6, 7, 9]], 'p.status' => ['neq', -1], 'p.create_time' => ['between', [$start_time, $end_time]]])
            ->select();
        $count = count($select_list);

        $list = Db::name('profit p')->join('shop_user u', 'p.user_id = u.id', 'left')
            ->distinct(true)->field('p.user_id,FROM_UNIXTIME( p.create_time, "%Y-%m-%d") date')
            ->where($search_where)
            ->where(['p.type' => ['IN', [1, 2, 3, 6, 7, 9]], 'p.status' => ['neq', -1], 'p.create_time' => ['between', [$start_time, $end_time]]])
            ->order('p.create_time desc')
            ->paginate(Config('paginate.list_rows'), $count)->each(function ($v) {
                // 消费收益
                $consume_profit = userAllProfit($v['user_id'], $v['date'], 1);
                $v['consume_profit'] = $consume_profit;
                // 绩效收益
                $achievements_profit = userAllProfit($v['user_id'], $v['date'], 2);
                $v['achievements_profit'] = $achievements_profit;
                // 服务津贴
                $service_profit = userAllProfit($v['user_id'], $v['date'], 3);
                $v['service_profit'] = $service_profit;
                // 门店区域补贴
                $shop_profit = userAllProfit($v['user_id'], $v['date'], 9);
                $v['shop_profit'] = $shop_profit;
                // 销售奖励
                $sales_profit = userAllProfit($v['user_id'], $v['date'], 6);
                $v['sales_profit'] = $sales_profit;

                // 退休基金
                $retire_profit = userAllProfit($v['user_id'], $v['date'], 7);

                $user_info = Db::name('user')->field('gear,mobile,username')->where(['id' => $v['user_id']])->find();
                $gear = $user_info['gear'];
                switch ($gear) {
                    case 'first_gear':
                        $v['first_retire_profit'] = $retire_profit;
                        $v['second_retire_profit'] = '0.00';
                        $v['third_retire_profit'] = '0.00';
                        break;
                    case 'second_gear':
                        $v['first_retire_profit'] = '0.00';
                        $v['second_retire_profit'] = $retire_profit;
                        $v['third_retire_profit'] = '0.00';
                        break;
                    case 'third_gear':
                        $v['first_retire_profit'] = '0.00';
                        $v['second_retire_profit'] = '0.00';
                        $v['third_retire_profit'] = $retire_profit;
                        break;
                    default:
                        $v['first_retire_profit'] = '0.00';
                        $v['second_retire_profit'] = '0.00';
                        $v['third_retire_profit'] = '0.00';
                        break;
                }
                $v['mobile'] = $user_info['mobile'];
                $v['username'] = $user_info['username'];

                $all_price = $consume_profit + $achievements_profit + $service_profit + $shop_profit + $sales_profit + $retire_profit;
                $v['all_price'] = sprintf('%.2f', $all_price);

                return $v;
            });

        $this->assign('list', $list);

        $this->assign('title', $date . ' 开支明细');
        return $this->view->fetch();
    }

    /**
     * 某天开支明细（二级）
     * */
    public function exportSpendCensusUserList()
    {
        $input = Request()->param();

        $date = $input['date'];
        $username = $input['username'] ? : '';
        $mobile = $input['mobile'] ? : '';

        $title = $date . '开支明细';
        $th = ['用户昵称', '手机号', '消费收益', '绩效收益', '服务津贴', '门店区域补贴', '销售奖励', '退休基金一档', '退休基金二档', '退休基金三档', '小计'];
        $td = ['username', 'mobile', 'consume_profit', 'achievements_profit', 'service_profit', 'shop_profit', 'sales_profit', 'first_retire_profit', 'second_retire_profit', 'third_retire_profit', 'all_price'];
        $data = getSpendCensusUserList($date, $username, $mobile);

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 收支明细（三级）
     * */
    public function spendCensusUserDetail()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $date = $input['date'];
        $type = $input['type'];

        if (empty($user_id)) adminReturn(2, '用户ID缺失');
        if (empty($date)) adminReturn(2, '日期缺失');


        if ($type) {
            $where['type'] = $type;
        } else {
            $where['type'] = ['IN', [1, 2, 3, 6, 7, 9]];
        }

        $start_time = strtotime($date);
        $end_time = $start_time + 60 * 60 * 24 - 1;

        $list = Db::name('profit')->field('order_id,type,price,create_time,remark')->where($where)->where(['user_id' => $user_id, 'create_time' => ['between', [$start_time, $end_time]]])->order('create_time asc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $user_info = Db::name('user u')->join('shop_order o', 'u.id = o.user_id', 'left')
                    ->field('u.id,u.username,u.mobile,u.gear,o.is_first_order')->where(['o.id' => $v['order_id']])->find();

                $v['username'] = $user_info['username'];
                $v['mobile'] = $user_info['mobile'];

                $v['create_time'] = timeFormat($v['create_time']);

                switch ($v['type']) {
                    case 1:
                        $count = 0;
                        getTreeCount($user_id, $user_info['id'], $count);
                        $type_desc = '消费收益';
                        $desc = ' 消费收益 ' . ($count > 0 ? '下' . $count . ' ' : '') . '[' . ($user_info['is_first_order'] ? '复消' : '首消') . ']';
                        break;
                    case 2:
                        $count = 0;
                        getTreeCount($user_id, $user_info['id'], $count);
                        $type_desc = '绩效收益';
                        $desc = ' 绩效收益 ' . ($count > 0 ? '下' . $count . ' ' : '') . '[' . ($user_info['is_first_order'] ? '复消' : '首消') . ']';;
                        break;
                    case 3:
                        $count = 0;
                        getTreeCount($user_id, $user_info['id'], $count);
                        $type_desc = '服务津贴';
                        $desc = '服务津贴 ' . ($count > 0 ? '下' . $count . ' ' : '') . '[' . ($user_info['is_first_order'] ? '复消' : '首消') . ']';;
                        break;
                    case 6:
                        $type_desc = '销售奖励';
                        $desc = $v['remark'];
                        break;
                    case 7:
                        $gear = $user_info['gear'];
                        $type_desc = ($gear == 'first_gear' ? '一档' : ($gear == 'second_gear' ? '二档' : '三挡')) . '退休基金';
                        $desc = $type_desc;
                        break;
                    case 9:
                        $type_desc = '门店区域补贴';
                        $desc = $v['remark'];
                        break;
                }


                $v['type_desc'] = $type_desc;
                $v['username'] = $user_info['username'];
                $v['desc'] = $desc;
            }
        } else {
            $list = [];
        }

        $this->assign('list', $list);

        $this->assign('title', '开支明细');
        return $this->view->fetch();
    }

    /**
     * 某用户开支明细（二级）
     * */
    public function exportSpendCensusUserDetail()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $date = $input['date'];
        $type = $input['type'] ? : 0;

        $username = Db::name('user')->where(['id' => $user_id])->value('username');

        $title = $username . $date . '开支明细';
        $th = ['用户昵称', '手机号', '奖励名称', '奖金金额', '时间', '说明'];
        $td = ['username', 'mobile', 'type_desc', 'price', 'create_time', 'desc'];
        $data = getSpendCensusUserDetail($user_id, $date, $type);

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 统计查询
     * */
    public function censusSearch()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($start_time) && empty($end_time)) {
            $order_where["pay_time"] = ["egt", strtotime($start_time)];
            $profit_where["create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $order_where["pay_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
            $profit_where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $order_where["pay_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
            $profit_where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $order_where['is_pay'] = 1;
        $order_where['is_del'] = 0;
        $order_where['back_order_sn'] = '';
        $order_time_list = Db::name('order')->distinct(true)->field('FROM_UNIXTIME( pay_time, "%Y-%m-%d") date')->where($order_where)->order('pay_time desc')->select();

        $profit_where['type'] = ['IN', [1, 2, 3, 4, 5, 6, 7, 9, 10, 11]];
        $profit_where['status'] = ['neq', -1];
        $profit_time_list = Db::name('profit')->distinct(true)->field('FROM_UNIXTIME(create_time, "%Y-%m-%d") date')->where($profit_where)->order('create_time desc')->select();

        $time_list = array_unique(array_merge(array_column($order_time_list, 'date'), array_column($profit_time_list, 'date')));

        if ($time_list) {
            $tmp_data = [];
            foreach ($time_list as $v) {
                $tmp_data[]['date'] = $v;
            }

            $tmp_sql = 'CREATE TEMPORARY TABLE shop_tmp(date varchar(100))';
            Db::query($tmp_sql);

            Db::name('tmp')->insertAll($tmp_data);

            $list = Db::name('tmp')->order('date desc')->paginate()->each(function ($v) {
                $start_time = strtotime($v['date']);
                $end_time = $start_time + 60 * 60 * 24 - 1;

                // 销售总额
                $each_order_where['pay_time'] = ['between', [$start_time, $end_time]];
                $each_order_where['is_pay'] = 1;
                $each_order_where['is_del'] = 0;
                $each_order_where['back_order_sn'] = '';
                $all_order_price = Db::name('order')->where($each_order_where)->sum('pay_price');
                $v['all_order_price'] = sprintf($all_order_price);

                $each_profit_where['create_time'] = ['between', [$start_time, $end_time]];
                $each_profit_where['status'] = ['neq', -1];
                // 应发收益统计
                $all_get_profit = Db::name('profit')->where($each_profit_where)->where(['type' => ['IN', [1, 2, 3, 6, 7, 9]]])->sum('price');
                $v['all_get_profit'] = sprintf($all_get_profit);

                // 冻结收益总额
                $all_frozen_profit = Db::name('profit')->where(['create_time' => ['between', [$start_time, $end_time]], 'status' => 1])->sum('price');
                $v['all_frozen_profit'] = sprintf($all_frozen_profit);

                // 充值总金额
                $all_recharge_profit = Db::name('profit')->where($each_profit_where)->where(['type' => 10])->sum('price');
                $v['all_recharge_profit'] = sprintf($all_recharge_profit);

                // 可用收益支付总额
                $all_pay_profit = Db::name('profit')->where($each_profit_where)->where(['type' => 4])->sum('price');
                $v['all_pay_profit'] = sprintf($all_pay_profit);

                // 微信支付总额
                $all_wx_pay_price = Db::name('order')->where($each_order_where)->where(['pay_type' => 1])->sum('pay_price');
                $v['all_wx_pay_price'] = sprintf($all_wx_pay_price);

                // 扣款总额
                $all_deduct_profit = Db::name('profit')->where($each_profit_where)->where(['type' => 11])->sum('price');
                $v['all_deduct_profit'] = sprintf($all_deduct_profit);

                // 成功提现总额
                $all_withdraw_profit = Db::name('profit')->where($each_profit_where)->where(['type' => 5])->sum('price');
                $v['all_withdraw_profit'] = sprintf($all_withdraw_profit);

                return $v;
            });

            $all_list = Db::name('tmp')->order('date desc')->select();
            $all_start_date = '';
            $all_end_date = '';
            foreach ($all_list as $k => &$v) {
                if ($k == 0) {
                    $all_end_date = $v['date'];
                } else if ($k + 1 == count($all_list)) {
                    $all_start_date = $v['date'];
                }

                $start_time = strtotime($v['date']);
                $end_time = $start_time + 60 * 60 * 24 - 1;

                // 销售总额
                $each_order_where['pay_time'] = ['between', [$start_time, $end_time]];
                $each_order_where['is_pay'] = 1;
                $each_order_where['is_del'] = 0;
                $each_order_where['back_order_sn'] = '';
                $all_order_price = Db::name('order')->where($each_order_where)->sum('pay_price');
                $v['all_order_price'] = sprintf($all_order_price);

                $each_profit_where['create_time'] = ['between', [$start_time, $end_time]];
                $each_profit_where['status'] = ['neq', -1];
                // 应发收益统计
                $all_get_profit = Db::name('profit')->where($each_profit_where)->where(['type' => ['IN', [1, 2, 3, 6, 7, 9]]])->sum('price');
                $v['all_get_profit'] = sprintf($all_get_profit);

                // 冻结收益总额
                $all_frozen_profit = Db::name('profit')->where(['create_time' => ['between', [$start_time, $end_time]], 'status' => 1])->sum('price');
                $v['all_frozen_profit'] = sprintf($all_frozen_profit);

                // 成功提现总额
                $all_withdraw_profit = Db::name('profit')->where($each_profit_where)->where(['type' => 5])->sum('price');
                $v['all_withdraw_profit'] = sprintf($all_withdraw_profit);

                // 充值总金额
                $all_recharge_profit = Db::name('profit')->where($each_profit_where)->where(['type' => 10])->sum('price');
                $v['all_recharge_profit'] = sprintf($all_recharge_profit);

                // 可用收益支付总额
                $all_pay_profit = Db::name('profit')->where($each_profit_where)->where(['type' => 4])->sum('price');
                $v['all_pay_profit'] = sprintf($all_pay_profit);

                // 微信支付的总额
                $all_wx_pay_price = Db::name('order')->where($each_order_where)->where(['pay_type' => 1])->sum('pay_price');
                $v['all_wx_pay_price'] = sprintf($all_wx_pay_price);

                // 扣款总额
                $all_deduct_profit = Db::name('profit')->where($each_profit_where)->where(['type' => 11])->sum('price');
                $v['all_deduct_profit'] = sprintf($all_deduct_profit);
            }
            $census = [
                'range_date' => ($input['start_time'] ? : $all_start_date) . ' - ' . ($input['end_time'] ? : $all_end_date),
                'all_order_price' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_order_price'))) : '0.00',
                'all_get_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_get_profit'))) : '0.00',
                'all_frozen_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_frozen_profit'))) : '0.00',
                'all_withdraw_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_withdraw_profit'))) : '0.00',
                'all_recharge_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_recharge_profit'))) : '0.00',
                'all_pay_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_pay_profit'))) : '0.00',
                'all_wx_pay_price' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_wx_pay_price'))) : '0.00',
                'all_deduct_profit' => $all_list ? sprintf('%.2f', array_sum(array_column($all_list, 'all_deduct_profit'))) : '0.00',
            ];
        }
        $this->assign('list', $list);
        $this->assign('census', $census ? : []);

        $this->assign('title', '统计查询');
        return $this->view->fetch();
    }

    /**
     * 导出统计查询
     * */
    public function exportCensusSearch()
    {
        $input = Request()->param();

        $start_time = $input['start_time'] ? : '';
        $end_time = $input['end_time'] ? : '';

        $title = '统计查询';
        $th = ['时间', '销售总额', '应发收益统计', '冻结收益总额', '充值总金额', '可用收益支付总额', '微信支付总额', '扣款总额', '成功提现总额'];
        $td = ['date', 'all_order_price', 'all_get_profit', 'all_frozen_profit', 'all_recharge_profit', 'all_pay_profit', 'all_wx_pay_price', 'all_deduct_profit', 'all_withdraw_profit'];
        $data = getCensusSearchData($start_time, $end_time);

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 设置视频号信息
     * */
    public function setVideoInfo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = 1;
            $img = $input['img'];
            $top_img = $input['top_img'];
            $name = $input['name'];
            $shop_name = $input['shop_name'];
            $video_count = $input['video_count'];
            $fs_count = $input['fs_count'];

            if (empty($img)) apiReturn(2, '请上传封面图');
            if (empty($img)) apiReturn(2, '请上传视频商场榜图片');
            if (empty($name)) apiReturn(2, '请输入视频号名称');
            if (empty($shop_name)) apiReturn(2, '请输入店铺名称');

            $data = [
                'img' => $img,
                'top_img' => $top_img,
                'name' => $name,
                'shop_name' => $shop_name,
                'video_count' => $video_count,
                'fs_count' => $fs_count,
                'update_time' => time()
            ];

            $res = Db::name('video_info')->where(['id' => $id])->update($data);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $info = Db::name('video_info')->where(['id' => 1])->find();
            $this->assign('info', $info);

            $this->assign('title', '设置视频号信息');
            return $this->view->fetch();
        }

    }

    /**
     * 下单列表
     * */
    public function chooseGoodsList()
    {
        $input = Request()->param();

        $one_type_id = $input['one_type_id'];
        $two_type_id = $input['two_type_id'];
        $is_stock = $input['is_stock'];
        $brand_id = $input['brand_id'];

        $where['upper'] = 1;
        if ($one_type_id) $where['one_type_id'] = $one_type_id;
        if ($two_type_id) $where['two_type_id'] = $two_type_id;
        if ($brand_id) $where['brand_id'] = $brand_id;

        if ($is_stock == 1) {
            $stock = C('STOCK_WARNING');
            $goods_ids = Db("sku_value")->where(["stock" => ['lt', $stock]])->group("goods_id")->column("goods_id");
            $where['id'] = ['in', $goods_ids];
        }

        $list = Db::name('goods')->where($where)->order('create_time desc')->paginate()->each(
            function ($item) {
                $item['one_type_name'] = Db::name('goods_type')->where(['id' => $item['one_type_id']])->value('name');
                $item['two_type_name'] = Db::name('goods_type')->where(['id' => $item['two_type_id']])->value('name');
                $item['brand_name'] = Db::name('goods_brand')->where(['id' => $item['brand_id']])->value('name');

                return $item;
            }
        );

        $type_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => 0])->select();
        if ($type_list) {
            foreach ($type_list as &$v) {
                $son_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => $v['id']])->select();
                $v['son_list'] = $son_list;
            }
        }
        //查询出品牌

        $brand_list = Db::name('goods_brand')->order('sort asc')->select();

        $this->assign('list', $list);

        $this->assign('type_list', $type_list);
        $this->assign('brand_list', $brand_list);
        $this->assign('type_list_json', json_encode($type_list, JSON_UNESCAPED_UNICODE));

        $user_id = cookie('id');
        $count = Db::name('admin_goods_car')->where(['user_id' => $user_id])->count();
        $this->assign('count', $count);

        $this->assign('title', '下单列表');

        return $this->fetch();
    }

    public function confirmOrder()
    {
        $operation_usre_id = cookie('id');

        $user_list = Db::name('user')->select();
        $this->assign('user_list', $user_list);

        $car_list = Db::name('admin_goods_car')->field('id,goods_id,img,sku_id,price,count')->where(['user_id' => $operation_usre_id])->select();
        $all_price = 0;
        if ($car_list) {
            foreach ($car_list as &$v) {
                $goods_info = Db::name('goods')->field('name,gift_ids')->where(['id' => $v['goods_id']])->find();
                $v['goods_name'] = $goods_info['name'];
                $v['img'] = getPicture($v['img']);
                $v['sku'] = implode(' / ', array_column(getSkuName(explode('-', $v['sku_id'])), 'name'));
                $all_price += sprintf("%.2f", $v['price'] * $v['count']);
            }
        }

        $this->assign('car_list', $car_list);
        $this->assign('all_price', $all_price);

        $this->assign('title', '确认订单');

        return $this->fetch();
    }

    /**
     * 会员统计
     * */
    public function userCensus()
    {
        $time_list = Db::name('user')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->where(['id' => ['gt', 1]])->order('create_time asc')->select();
        $user_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $user_count = Db::name('user')->where(['id' => ['gt', 1]])->where($where)->count();
                $user_list[] = $user_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('user_list', json_encode($user_list));

        $this->assign('title', '会员统计');

        return $this->fetch();
    }

    /**
     * 商品统计
     * */
    public function goodsCensus()
    {
        $time_list = Db::name('goods')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->order('create_time asc')->select();
        $user_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $user_count = Db::name('goods')->where($where)->count();
                $user_list[] = $user_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('user_list', json_encode($user_list));

        $this->assign('title', '商品统计');

        return $this->fetch();
    }

    /**
     * 交易统计
     * */
    public function orderCensus()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($start_time) && empty($end_time)) {
            $where["pay_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["pay_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["pay_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        // 下单人数
        $pay_user_list = Db::name('order')->distinct(true)->field('user_id')->where(['is_pay' => 1])->where($where)->select();
        $pay_user_count = count($pay_user_list);
        $this->assign('pay_user_count', $pay_user_count);

        // 下单笔数
        $pay_order_count = Db::name('order')->where(['is_pay' => 1])->where($where)->count();
        $this->assign('pay_order_count', $pay_order_count);

        // 下单金额
        $pay_order_price = Db::name('order')->where(['is_pay' => 1])->where($where)->sum('pay_price');
        $this->assign('pay_order_price', sprintf('%.2f', $pay_order_price));

        // 时间轴
        $time_list = Db::name('order')->field("from_unixtime(pay_time, '%Y-%m-%d') time")->distinct(true)->where(['is_pay' => 1])->where($where)->order('pay_time asc')->select();
        if($time_list){
            // 付款金额
            $pay_price_arr = [];
            // 付款笔数
            $pay_order_arr = [];
            // 付款人数
            $pay_user_arr = [];
            foreach($time_list as &$v){
                $map['pay_time'] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $pay_price = Db::name('order')->where(['is_pay' => 1])->where($map)->sum('pay_price');
                $pay_price_arr[] = sprintf('%.2f', $pay_price);

                $pay_order = Db::name('order')->where(['is_pay' => 1])->where($map)->count();
                $pay_order_arr[] = $pay_order;

                $pay_user_list = Db::name('order')->distinct(true)->field('user_id')->where(['is_pay' => 1])->where($map)->select();
                $pay_user_arr[] = count($pay_user_list);
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time'), JSON_UNESCAPED_UNICODE));
        $this->assign('pay_price_arr', json_encode($pay_price_arr, JSON_UNESCAPED_UNICODE));
        $this->assign('pay_order_arr', json_encode($pay_order_arr, JSON_UNESCAPED_UNICODE));
        $this->assign('pay_user_arr', json_encode($pay_user_arr, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '交易统计');

        return $this->fetch();
    }
}
